Manage Resource Events

Resource events are JavaScript code that  executes for each row of your table-based resources. You can create resource events that conditionally discard rows, that inject computed resource attributes, or that perform lookups in other entities within your API.
lac52
Resource events are JavaScript code that 
Layer7 Live API Creator
 executes for each row of your table-based resources. You can create resource events that conditionally discard rows, that inject computed resource attributes, or that perform lookups in other entities within your API.
Table-based resources can includes GET and PUT/POST events. Free SQL resources can include only GET events.
For more information about the tasks that each endpoint type supports, see Customize your API.
In this article:
 
 
3
 
 
GET Events
 
Layer7 Live API Creator
 executes the JavaScript code for these events when it receives a GET call on the resource endpoint and after it reads the data from the data source. GET events can delete rows, can add or drop resource attributes from a row, and can compute data. In table-based resources, GET events can compute and populate virtual resource attributes and can perform code-based lookups.
Example:
 
The following GET event populates the 
product_name
 virtual resource attributes (the 
virtuals
 variable) using the following JavaScript code:
var params = {
usingValues: {
product_number: tableRow.product_id
}
};
var products = SysUtility.findEntities("demo:product", params);
if (null !== products && products.length > 0) {
virtuals.product_name = products[0].name;
}
For more information:
PUT/POST Events
 
Layer7 Live API Creator
 executes the JavaScript code for these events when it receives a PUT or POST call on the resource endpoint, before it sends the row to the database, and before it processes row-based logic. You can use PUT/POST events to perform lookups to populate foreign keys (even if the keys are not displayed).
Example:
 
The 
row
 object contains the PUT or POST payload. The 
tableRow
 object contains the values that 
Layer7 Live API Creator
 sends to the database before it processes logic:
var params = { lookupValues:
{ name: row.product_name }
};
var products = SysUtility.findEntities("demo:product", params);
if (null !== products && products.length > 0) {
tableRow.product_id = products[0].product_number;
}
For more information about the 
findEntities()
 method, see The SysUtility Object.
Create a Resource Event
Prerequisite:
 The table-based or Free SQL resource to which you want to add a resource event exists.
  1. With your API open, in the Create section, click 
    Resources
    .
    A list of resources display.
  2. Select the resource for which you want to create a resource event from the resource list, and then click the
     Events
     tab.
    The 
    GET Event
     subtab is selected by default.
  3. Click the subtab (
    GET Event
     or 
    PUT/POST Event
    ) for the event type that you want to create.
    For more information about the event types, see the "GET Event" section and the "PUT/POST Event" section.
  4. Enter JavaScript code that defines the resource event in the code editor.
    You can access and insert a JavaScript code example into the resource event code editor. For more information about the code examples that are available for resource events, see JavaScript Code Examples.
    You can use the following context variables and objects in the JavaScript code for your resource event:
     
    Context variables and objects
    Variable/Object
    GET Events
    PUT/POST Events
     
     row 
     
     
    yes
     
     
    yes
     
     
    yes
     
     
    yes
     
     
    yes
     
     
    yes
     
     
    yes
     
     
    yes
     
     
    yes
     
    no
      
     
    yes
     
    no
     
    yes
     
     
    yes
     
     
    yes
     
     
    yes
     
     
    yes
     
     
    yes
     
     
    yes
     
     
    yes 
     
  5. Save your changes.
Your resource event is created.
Inject Computed Resource Attributes
You can reference an NPA in an entity resource attribute, and then create a GET event to inject computed resource attributes or to calculate simple values.
Prerequisite:
 
  • You have added the NPA to your data source.
  • You have added the entity resource attribute that references the NPA.
The 
B2B Northwind
 API sample includes the 
EmployeesWithRaises
 resource that illustrates the 
FullNameNPA
 entity resource attribute and a GET event reference to the 
logicRow
 attribute's NPA.
Create the GET event, defining the code that references the NPA.
Context Variables and Objects for Resource Events
You can use the following context variables and objects in the JavaScript code for your resource event:
The row Variable
The 
row
 variable contains the value of the row in its current state. In the context of GET events, you can change the value of the 
row
 object and add, change, or remove attributes. You can retrieve values from the 
row
 object just as you do from any JavaScript object.
You can change the values of the 
row
 variable, but the client sees data that does not correspond to what is actually in the database. If you change the value of an attribute in the 
row
 variable, you can only update this variable by overriding the 
checksum
 value.
You can also add new values, like a computed value.
 Best Practice:
 If you plan to define aliases for your resource attributes, use the 
tableRow
 variable in your GET events.
Use the following syntax:
row['parentRoleName'].['parentResAttrName']
Examples:
 
If you want only a specific customer to have the 
full_name
 attribute, composed of the customer's first name and last name, you can add a customers filter to a resource using the following syntax:
if (row.custnum === 1234) {
row.full_name = row.first_name + ' ' + row.last_name;
}
You can also add the attributes using a more complicated JavaScript object or array, for example:
if (row.custnum === 1234) {
row.name_info = {
'First': row.first_name ,
'Last' : row.last_name,
'FullName': row.first_name+ ' ' + row.last_name
}
}
Best Practice:
 If you are using an existing system and you cannot change the database schema, add an NPA to your data source, and then reference it from table-based resources. For more information about how to add NPAs and use them in resources, see Manage Non-Persistent Attributes.
If you do not want 
Layer7 Live API Creator
 to send the row to the client, you can filter out the row, for example:
if (row.username == 'DoNotShow') {
row = null;
}
 
Layer7 Live API Creator
 records the attributes that you add to the 
@metadata
 section as 
nonpersistent
Layer7 Live API Creator
 records the attributes that you remove to the 
@metadata
 section as 
removedAttributes
.
You can update rows only for table-based resources.
The containingRow Variable
The 
containingRow
 variable is the row in the parent resource. Only child resources can access this variable. Root resources cannot access the variable because they do not have parents.
Example:
 
var result = {
/* some content here */
};
if (containingRow && containingRow.company_name) {
result.orgName = containingRow.company_name;
}
return result;
The tableRow Variable
The 
tableRow
 variable contains the attributes that 
Layer7 Live API Creator
 reads from the database. It provides 
Layer7 Live API Creator
 access to the database record after it has applied security, and it ignores changes.
 Best Practice:
 If you plan to define aliases for your resource attributes, use the 
tableRow
 variable in your GET events.
The parentRow Variable
If the resource is a subresource, and the API user is accessing it by way of its containing resource (for example, the API user is accessing the subresource using the 
/MyParent
 URL instead of directly with the 
/MyParent.MyChild
 URL), then the 
parentRow
 variable is defined. The resource contains the parent row.
 Do not alter the content in the parent row. The parent row is for reference only.
Example:
 
You can check if the 
parentRow
 variable is 
null
 using the following syntax:
// parentRow may be null, need to check first
if (parentRow) {
row.full_name = parentRow.name + '.' + parentRow.name;
}
The logicRow Variable
In the context of a resource GET event, the 
logicRow
 variable has full access to resource attributes, parents, and children of the resource row. You can use these values to do lookups and to populate the 
virtuals
 variable.
Use the following syntax:
logicRow.['parentRoleName'].['parentResAttrName']
Example:
 
var lookupValue = logicRow.myParent.myAttribute;
virtuals.MyParentAttribute = lookupValue;
The virtuals Variable
In the context of a GET event, the 
virtuals
 variable contains the virtual resource attributes that have been added to the resource. Use this variable in a GET event to set the value of a virtual resource attribute.
Use the following syntax:
virtuals.['virtualResAttrName'] = 'Some Value';
In the context of a PUT/POST event, the 
row
 variable contains the values that the API user passes into API Server for the selected entity, optionally including virtual resource attributes. You can perform lookups and populate the 
row
 variable using these values.
The SysUtility Object
The 
SysUtility
 object exposes RESTful services, such as the 
getHostName()
 and 
restGet()
 methods.
For more information about these services, see The SysUtility Object.
The log Object
The 
log
 object is a logger object. You can use it to output arbitrary text as part of the request log.
For more information about this object, see The log Object.
The resource Variable
The 
resource
 variable provides access to the definition of the resource that you are filtering. 
Layer7 Live API Creator
 passes the resource definition as this variable. This variable has the following methods:
  •  
    getAttributes()
     method returns a list of the attributes that are defined for this resource. Each attribute has a 
    name
     , a 
    columnName
     , and a 
    format
     (if defined). 
  •  
    getJoinCondition()
     method returns a string, which contains the raw definition of the join to the parent resource, for example, 
    parent_ident = [ident]
     .
  •  
    getName()
     method returns the name of the resource, for example 
    MyChild
     .
  •  
    getNodalName()
     method returns the full name of the resource, for example, 
    MyParent.MyChild
     .
  •  
    getTableName()
     method returns the name of the table for which the resource was defined.
  •  
    getTopResource()
     method returns the top resource in the resource tree.
Example:
 
var i;
for (i = 0; i < resource.getAttributes().length(); i++) {
var attribute = resource.getAttributes().get(i);
}
The req Object
The 
req
 object contains the information from the available request, such as the apikey and verb. This object describes the request that 
Layer7 Live API Creator
 is processing.
For more information about the 
req
 object, see The req Object.
Example: Use a Resource Event
 The following example illustrates:
  • Skipping row
  • Accessing database row before aliasing.
  • Adding properties to output JSON.
  • Using unicode.
  • Erasing values (property set to null).
  • Using a property name that is not valid with dot notation.
  • NPA property that 
    Layer7 Live API Creator
     adds to 
    @metadata
     section.
    For more information about complex transaction processing, including how to use metadata action tags, see Complex Transaction Processing.
The following example uses the 
CustomerBusinessObject
 resource that is in the 
Demo
 API sample.
Follow these steps:
 
  1. Open the 
    Demo
     API.
  2. In the Create section, click 
    Resources
    .
    A list of resources display.
  3. Select the 
    CustomerBusinessObject
     resource from the list, and then click the
     Events
     tab.
    The GET Event tab appears.
  4. Enter the following JavaScript code as the GET event into the code editor, and then save your changes:
    if (row.name === 'Alpha and Sons') {
    // skipping a row
    row = null;
    }
    else if (row.name === 'Bravo Hardware') {
    // Adding properties to output JSON
    // Erasing value (property set to null).
    row.foo = 'Hi there!';
    row["2xbalance"] = 2 * tableRow.balance;
    row.credit_limit = null;
    }
    else if (tableRow.name === 'Charlie\'s Construction') {
    // show some love
    row.name = '\u2764 ' + tableRow.name + ' \u2764';
    }
  5. Test this resource event in the REST Lab by clicking 
    Test
    .
  6. Observe the additional attributes and the 
    @metadata
     changes for those affected rows.
For more information about how to test resource events in the REST Lab, see Test your API Using the REST Lab.