Developing APIs‎ > ‎Extensibility‎ > ‎

The Req Object

The req object is available to all rules and event handlers as the req variable. This object is created once per request. Its contents are discarded when the request is complete. The req object is suitable for transaction state but not for state that transcends requests.

The req object has the following attributes:

 Attribute name TypeDescription
 clientAddress stringThe IP address of the client who initiated the request.
 clientUsesHttps booleanTrue 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 ApiKeyThe API key used to authenticate the request.
 apiVersion ApiVersionThe API version object. You can get its name by calling getName() (for example, "v1" ).
 verb stringGET, POST, PUT, DELETE
 resourceName stringThe name of the resource/table on which the request is performed.
 baseUrl stringThe base URL for this request.    
 localBaseUrl stringThe 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 stringThe full base URL for this request, including the API version.
 localFullBaseURL stringThe 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 objectAll the HTTP headers that were provided by the caller, except the authentication header. The header names are case-insensitive. Example: req.httpHeaders['user-agent'].

Note: 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.

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 like this:

arg.argName=true

Access them in your logic, like this: 

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:

Examples

// 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";

// Deletes must be over HTTPS
if (req.verb == "DELETE" && !req.clientUsesHttps)
    throw "Delete must be over HTTPS";

// 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 Logic Demo, the event: "Audit Purchase Order amount changes", and observe its effect in the log.

Note: For this to work in Logic Demo, you must update the auth token for Broad Access 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]));

Request properties/methods

Sample

Description

fullBaseURL

https://rest.acme.com/rest/default/data/v1/ 

 

getKeepTransactionSummary

 boolean 

 

apiKeyId

 1003

 

getAccountOption

 String

 

hashCode

 int

 

wait

 int

 

unsetUserProperty

 Object

 

close

 close()

 

getContext

 LogicTransactionContext

 

startTime

 166557061561680 

 

baseUrl

 https://rest.acme.com/rest/default/data/

 

getInlineDecider

 InlineDeferDecider

 

userProperty

 undefined

 

getEntityPermission

 EntityPermission

 

customResources

 {}

 

getUserProperties

 java.util.Map

 

deferredAttributeParam

 String

 

isClosed

 boolean

 

resourceName

 main:customer

 

notifyAll

 function

 

inlineDecider

 

 

statusParams

 

 

equals

 

 

status

 

 

class

 

 

isRuleSummaryEnabled

 

 

setUserProjectIdent

 

 

setRuleSummaryEnabled

 

 

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

 

 

setUserProperty

 

 

loggingOptions

 

 

dataStoreConnectionManager

 DataStoreConnectionManager

 

uriInfo

 

 

getApiVersion

 

 

metadata_name

 @metadata

 

hasUserProperty

 boolean

 

httpCode

 0

 

requestIdent

 1650286061_166557061558110

 

requestSequenceId

 3

 

debug

 false

 

isTxSummaryEnabled

 boolean

 

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 ] 

 

getUserProperty

 

 

statusCode

 

     

procInlineLimit

 2000

 

userAccountIdent

 1000

 

verb

 GET, PUT, POST, DELETE

 

json

 {}

 

urlParameters

  { "inlineamount": "0", "deferred": "content" } 

 

chunkSize

2000 

 

notify

 

 

inlineLimit

 6000

 

closed

 boolean

 

clientUsesHttps

 boolean

 

getClass

 

 

apiVersion

 function

 

userProperties

 

 

getHttpCode

 

 

apiVisibilityPermission

 

 

inlineAttributeParam

 null

 

getAccount

 function

 

getApiKey

 function

 

clientAddress

 null

 

txSummaryEnabled

 boolean

 

getFullBaseURL

 function

 

entityPermission

 undfined

 

setTxSummaryEnabled

 function (boolean)

 

getProject

 function

 

keepTransactionSummary

 boolean

 

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

 

More Information

For more information about how to use the JSON object, including the stringify(<value>) JSON object function, see JavaScript.