The Req Object

The Req Object
lac31
You can access the 
req
 object from rules and event handlers as the
req
 variable. This object is created once per request. 
CA Live API Creator
 discards its contents when the request is complete.
The
req
 object is suitable for transaction state but not for state that transcends requests.
In this article:
Attributes
The 
req
 object includes the following attributes:
Attribute
Type
Description
clientAddress
string
The IP address of the client who initiated the request.
clientUsesHttps
boolean
True if the request is over HTTPS.
False if the request is over HTTP.
urlParameters
object
 All the parameters, and their values, as specified in the URL (for example, 
req.urlParameters.<paramName>
).
apiKey
ApiKey
The API key used to authenticate the request.
apiVersion
ApiVersion
The API version object. You can get its name by calling 
getName()
 (for example, "v1" ).
verb
string
GET, POST, PUT, DELETE
resourceName
string
The name of the resource/table on which the request is performed.
baseUrl
string
The base URL for this request.    
localBaseUrl
string
The base URL for this request, but corrected to use 
localhost
 as the host. Use this attribute if you need to talk (that is, loopback) to the local API.
fullBaseURL
string
The full base URL for this request, including the API version.
localFullBaseURL
string
The full base URL for this request, but corrected to use
localhost
as the host. Use this attribute if you need to talk (that is, loopback) to the local API.
httpHeaders
object
All the HTTP headers that were provided by the caller, except the authentication header. The header names are case-insensitive. Example:
req.httpHeaders['user-agent']
.
Strings in the 
req
 object are Java strings internally. As a result, use care when using equality tests. While they perform just like JavaScript strings, when using '===' or '!==' equality tests, they are not the same and results can be unexpected. For example,
"GET" === req.verb
is always false, where
"GET" == req.verb
is true on a GET request.
Properties/Methods
The 
req
 object has the following properties/methods:
Property/Method
Type
Example
fullBaseURL
string
getKeepTransactionSummary
boolean
True
apiKeyId
string
1003
getAccountOption
string
hashCode
int
wait
int
unsetUserProperty
Object
close
function
close()
getContext
LogicTransactionContext
startTime
166557061561680 
getInlineDecider
InlineDeferDecider
userProperty
undefined
getEntityPermission
EntityPermission
customResources
{}
deferredAttributeParam
string
isClosed
boolean
resourceName
main:customer
notifyAll
function
inlineDecider
statusParams
equals
function
status
class
isRuleSummaryEnabled
boolean
True
setUserProjectIdent
function
setRuleSummaryEnabled
function
project
Data Row (map): [authprovider_ident: 1000, ts: 2015-01-23 14:59:50.0, ident: 1001, is_active: true, status: null, name: AlfrescoDocTest, account_ident: 1000, comments: null, url_name: data ] :
userProjectIdent
ruleSummaryEnabled
boolean
getApiVisibilityPermission
 ApiVisibilityPermission 
responseFormat
 null
toString
loggingOptions
dataStoreConnectionManager
DataStoreConnectionManager
uriInfo
getApiVersion
metadata_name
@metadata
hasUserProperty
boolean
True
httpCode
0
requestIdent
1650286061_166557061558110
requestSequenceId
3
debug
boolean
false
isTxSummaryEnabled
boolean
false
projectId
1001
apiKey
Data Row (map): [default_access: null, ts: 2015-01-14 22:43:34.0, ident: 1003, expiration: null, status: A, description: null, name: Broad access, origin: null, data: user = 'Tyler', logging: *=FINE, project_ident: 1001, user_identifier: null, apikey: data_full ] 
statusCode
procInlineLimit
2000
userAccountIdent
1000
verb
GET, PUT, POST, DELETE
json
{}
urlParameters
{ "inlineamount": "0", "deferred": "content" } 
chunkSize
2000 
notify
inlineLimit
6000
closed
boolean
True
clientUsesHttps
boolean
True
getClass
apiVersion
function
userProperties
getHttpCode
apiVisibilityPermission
inlineAttributeParam
null
getAccount
function
getApiKey
function
clientAddress
null
txSummaryEnabled
True
getFullBaseURL
function
entityPermission
undefined
setTxSummaryEnabled
function (boolean)
getProject
function
keepTransactionSummary
boolean
True
context
LogicTransactionContext
getDataStoreConnectionManager
account
Data Row (map): [ts: 2015-01-08 20:47:21.0, ident: 1000, status: A, private_key: null, name: el-local account, public_key: null, url_name: el-local 
txLog
TransactionLog
accountOption
undefined
getUserProjectIdent
function
The req Object Methods
The
req
object has the following methods:
baseUrl() Method
You can retrieve the base URL for the request, up to and including the API name, using the 
baseUrl()
 method. This method uses the following syntax:
[http: || https]://[server.company.com[:port[/ServerWAR]] ]/[rest || data]/[TeamSpace name]/[URL fragment]/
Example:
https://rest.acme.com/rest/default/data/
getUserProperty() Method
Use the 
getUserProperty()
 method to retrieve an arbitrary object from the request object, as previously set by the 
setUserProperty()
 method.
This method uses the following syntax:
req.getUserProperty(string, object)
setUserProperty() Method
Use the 
setUserProperty()
 method to set the specified API user property to the given value. After you have set the API user property, a piece of JavaScript code can retrieve the API user property in the scope of the request. 
This method uses the following syntax:
req.setUserProperty(name, object)
getUserProperties() Method
Use the 
getUserProperties()
 method to retrieve the URL properties/values where the property starts with 
arg
Example:
req.getUserProperties().get("argName")
For more information about an example of how to use this method, see the "Access HTTP Arguments" section.
The apiKey Object Methods
The 
apiKey
 object has the following methods:
The getUserIdentifier() Method
You can retrieve the login ID (userIdentifier) from the authentication token using the 
getUserIdentifier()
 method. 
The following code example illustrates how you can get the name for an API user name within the authentication token:
var apiKey = req.getApiKey(); // apiKey as object
var login = 
apiKey.getUserIdentifier()
;
log.debug("** Get the login ID: " + login); // gets the login ID as string
The getDataObjects() Method
You can access information about the API user that your authentication provider passes in using the the 
getDataObjects()
 method.
The following code example illustrates how to retrieve name/value pair information for an API user that is stored in the 
userData
 object of your HTTP authentication provider using this method:
var temp = req.apiKey
.getDataObjects
().get("abc");
log.debug("** The abc user data: " + temp);
For more information about how to authenticate API users using the HTTP authentication provider, see Authentication.
HTTP Arguments
You can access arguments supplied in the HTTP request by way of the 
request
 object. You can test these in your logic, which enables you particularize your update requests.
For more information:
Supply HTTP Arguments
Use the following syntax to supply HTTP arguments:
arg.argName=true
Access HTTP Arguments
Use the following syntax to access HTTP arguments in your logic:
req.getUserProperties().get("argName")
Transaction State
The
userProperties
object is initialized when the request begins, but you can also update and test it for transaction state. For example, the following code ensures that only one supplier alert is raised, even if multiple items are purchased for the supplier Pavlov:
The following code snippet rejects requests that do not originate from the allowed IP range:
// Reject requests that do not originate from the allowed IP range
if ( ! req.clientAddress.match(/^12\.34\.56\./g))
   throw "Requests are not allowed from this IP address";
The following code snippet requires deletes to be over HTTPS:
// Deletes must be over HTTPS
if (req.verb == "DELETE" && !req.clientUsesHttps)
   throw "Delete must be over HTTPS";
The following code snippet requires that you provide a special parameter to create a new widget:
// We require a special parameter to create a new Widget
if (req.verb == "POST" && req.resourceName == "Widget") {
   var special = req.urlParameters.specialParam;
   if (special != "Please")
      throw "You forgot the magic word.";
}
log.debug("clone event start");
if (req.urlParameters.clone !== null) {
  log.debug("cloning: " + row);
  var deepCopy = ["lineitemsList"];
  SysLogic.copyTo("orders", logicContext, deepCopy, false); 
  }
In the following example, you get a users name by way of their login. The
request
object provides access to the auth token. You can obtain the login ID (
userIdentifier
) using this auth token so that you can query the 
employees
table. You can substitute this code into into Demo API sample, the
Audit Purchase Order amount changes
event rule, and observe its effect in the log.
For this request to work in the Demo API sample, you must update the
Broad Access
auth token to User Identifier
sam
.
if ("INSERT" != logicContext.initialVerb && row.amount_total != oldRow.amount_total) {
  // for (var i in req) { log.debug("Audit Purchase Order - req " + i); }
  var apiKey = req.getApiKey(); // apiKey as object
  log.debug("Audit Purchase Order with apiKey: " + apiKey.getApiKey()); // gets apiKey as string
  // for (var i in apiKey) { log.debug("Audit Purchase Order - apiKey " + i); }
  var login = apiKey.getUserIdentifier();
  log.debug("Audit Purchase Order with userName: " + login); // gets apiKey as string
  sql = "select * from employee where login = " + "'" + login + "'";
  var employee = logicContext.getBeanByUniqueAttributes("demo:employee", ["login"], [login]);
  log.debug("Audit Purchase Order for Employee: " + employee); // row has user's name, etc..
  // or, use Globals (you must set them first [Role > Globals], may require ApiKeys > User Identifier)
  employee = logicContext.transactionContext.permissionContext.getData("current_employee_row");
  log.debug("Audit Purchase Order for Employee from Global: " + employee); // <=== hmm, it's null
  var newPurchaseorder_audit = logicContext.createPersistentBean("purchaseorder_audit");
  newPurchaseorder_audit.amount_total = oldRow.amount_total; // set attributes from old values
  newPurchaseorder_audit.paid = oldRow.paid;
  newPurchaseorder_audit.customer_name = oldRow.customer_name;
  newPurchaseorder_audit.order_number = oldRow.order_number; // set the foreign key
  logicContext.insert(newPurchaseorder_audit); // saves (fires logic)
}
// an alternative when the new values are wanted
// if ("INSERT" != logicContext.initialVerb && row.amount_total != oldRow.amount_total)
// SysLogic.insertChildFrom("purchaseorder_audit", logicContext);
Debug Tips
You can explore the
request
object's contents using code. For example:
var json = JSON.parse(req.json);
for (var i in req) { log.debug("****req " + i); }
for (var i in JSON.parse(req.json)) { log.debug("!!!!!json " + i); }
var custName = json.customer; // a value in the request
log.debug("***custName: " + custName);
var options = { filter: "name = '" + custName + "'" };
log.debug("***options: " + options);
var custAccount = SysUtility.getResource("cust", options);
for (var i in custAccount) { log.debug("@@@@ " + i); }
log.debug("***sending message" + JSON.stringify(custAccount[0]));
For more information about how to use the JSON object, including the 
stringify(<value>)
 JSON object function, see JavaScript.