Define JavaScript Resource Types

You can get full control over returned JSON by defining JavaScript resource types. JavaScript resources are not explicitly bound to tables, such as other web services. Your JavaScript code is responsible for retrieving data and for formatting it into JSON. The most common use for this resource type is to call an outside REST service and connect to multiple servers of any type. For example, you might aggregate REST/JSON services.
lac52
You can get full control over returned JSON by defining JavaScript resource types. JavaScript resources are not explicitly bound to tables, such as other web services. Your JavaScript code is responsible for retrieving data and for formatting it into JSON. The most common use for this resource type is to call an outside REST service and connect to multiple servers of any type. For example, you might aggregate REST/JSON services.
You can provide options on how you want 
Layer7 Live API Creator
 to handle incoming requests for your JavaScript resources by defining the extended properties for the resource.
For more information about how to define extended properties for a resource, see Manage the Extended Properties for Resources.
 
Layer7 Live API Creator
 does not understand the internals of the external content, including its mapping to underlying data, its primary keys, its logic, and its security. 
Layer7 Live API Creator
 cannot supply advanced automation services such as pagination or update.
In this article:
 
 
2
 
 
Create a JavaScript Resource
  1. With your API open, in the Create section, click 
    Resources
    .
    If you have not defined any resources yet, the Welcome to Resources page appears. If you have created at least one resource, the Resource tab displays.
  2. Do one of the following options:
    • If you have not defined a resource yet, create a resource by clicking 
      Create a Resource
      .
    • If you have created at least one resource, above the list of resources, click 
      New Resource
      .
    The Add Resource window opens.
  3. Complete the following fields, and then click 
    Add
    :
    Resource Type
     
    Defines the type of resource you want to create. Select 
    JavaScript Resource
    .
    Values:
     
    • Ⓣ Table-based Resource.
       Resources that are linked to existing base SQL entities (tables and views) and automate SQL handling. You can integrate other data sources and control SQL by defining the resource type.
    • Ⓢ Free SQL
       Resource
      . Resources that you specify the SQL to execute.
    • Ⓙ JavaScript
       Resource
      . (Advanced users) Resources that you supply the server-side JavaScript that 
      Layer7 Live API Creator
       executes whenever the resource is accessed and returns JSON.
    Default:
     Table-based
    Resource Name
     
    The resource name is the container name with JSON. The name must contain alphanumerics or the underscore (_) special character.
    Unique:
     Yes
Your JavaScript resource is created and displays in the list of resources.
Define the JavaScript Resource
Top-level resources should be collections. Sub-resources are collections if there can be many rows for a single row in the containing resource. If a sub-resource is for an entity that is a parent entity of the containing resource's entity, then 
With your JavaScript resource open, complete the following fields, and then click 
Save
:
Is a collection
 
Defines whether the entity (table or view) for the resource is a child of the containing resource's entity.
Default:
 Selected
Code
 
Defines the server-side JavaScript code that API Server executes when an API user accesses this resource. The code is responsible for retrieving data and for formatting it into JSON.
Unique:
 Yes
For an example of how to define the code for your JavaScript resource, see the "Example JavaScript Resource" section.
Default:
 
var result = {
result: "Hello, world!",
String: "rkxgohwzng",
Number: 827.3783957232455,
"Null value": null
};
return result;
You can access and insert JavaScript code examples into the JavaScript resource code editor. For more information about the code examples that are available for JavaScript resources, see JavaScript Code Examples.
The details of your JavaScript resource is defined.
Example JavaScript Resource
The 
OrdersRest
 JavaScript subresource illustrates how you can deliver JSON results combining managed data (
CustomerJSOrdersREST
) with external service results (
OrdersRest
) by retrieving resource information from another REST server (line 2) as the data for the 
OrdersRest
 subresource.
The following code snippet shows the code for the 
OrdersRest
 JavaScript subresource that is included with the 
Demo
 API:
The 
Service calls to integrate external data
 code example is available from the JavaScript resource code editor.
var url = req.baseUrl;
log.debug(url); // this is the base URL for this server
url = url.replace("/demo","/sample");// compute baseURL of target system
url = url + "v1/orders"; // add version/ resource endPoint on target
var key = containingRow.name; // containingRow is system supplied
log.debug("..using key: " + key + ", and url: " + url);
key = JSON.stringify(key, null, 0);
var params= {
sysfilter: "equal(customer_name:" + key + ")"
};
//special Auth Token in this project to allow access from url (?auth=AdminKey:1)
var settings = {
headers: {
Authorization: "CALiveAPICreator AdminKey:1"
}
}
//////////// Built in utility to make REST GET call
var response = SysUtility.restGet(url, params, settings);
return JSON.parse(response);
For more information about the 
Demo
 API sample, see Demo API Sample.
Output
Your returned JSON (
OrdersRest
) is inserted into the larger result, as shown in the following code snippet:
{
"name": "Alpha and Sons",
"balance": 4484,
"@metadata": {
"href": "http://localhost:8080/APIServer/rest/el-local/demo/v1/CustomerJSOrdersREST/Alpha%20and%20Sons",
"checksum": "A:e86aea2e0a4e74bf"
},
"OrdersRest": [
{
"order_number": 1,
"amount_total": 1079,
"paid": false,
"notes": "This is a small order",
"customer_name": "Alpha and Sons",
"salesrep_id": 2,
"@metadata": {
"href": "http://localhost:8080/APIServer/rest/el-local/demo/v1/PurchaseOrders/1",
"checksum": "A:5c157e88a42aa592"
},
"LineItems": [
{
"lineitem_id": 12,
"product_number": 2,
"order_number": 1,
Context
The 
OrdersRest
 JavaScript subresource in the Demo API shows how your code includes context for:
  • The 
    containingRow
     JavaScript context variable. You can access data from the containing row, in the previous example, a Customer row from the 
    CustomerJSOrdersREST
     containing resource (line 3). You can "parameterize" the external service using locally managed data using the 
    containingRow
     JavaScript context variable.
  • The 
    log
     JavaScript context variable. This object is for printing to the log. You can view debugging information in the log.
    For more information about how to view logging information, see View Logging Information.
  • The 
    restCaller
     context variable. You can use this variable to invoke REST services, such as GET.
  • The 
    req
     object. Provides access to the HTTP request, including the API key, resource name, and arguments. This object has the following useful properties:
    return {
    baseUrl: "" + req.baseUrl, // The URL of this call up to the project
    fullBaseUrl: "" + req.getFullBaseURL(),
    accountName: "" + req.account.getName(),
    accountUrl: "" + req.account.getUrlName(),
    projectName: "" + req.project.getName(),
    projectUrl: "" + req.project.getUrlName(),
    apiName: "" + req.apiVersion.getName(),
    userIdentifier: "" + req.userIdentifier, // Can be null
    params: JSON.parse("" + req.urlParameters), // Parameters from URL, e.g. ?abc=123&def=foo
    userProps: JSON.parse("" + req.userProperties), // User props from authentication
    verb: "" + req.verb, // GET, POST, PUT, DELETE, etc...
    clientAddress: "" + req.clientAddress // The IP address of the caller
    };
    For more information about the 
    req
     object, see The req Object.
For more information about the context variables that are set when 
Layer7 Live API Creator
 invokes JavaScript logic, see the Quick Reference Guide.
Call JavaScript Resources
You can call JavaScript resources in the following ways:
Call JavaScript Resources as Endpoints
You can invoke an endpoint from the current API using the 
SysUtility.getResource()
 method in your JavaScript code. This method uses the same authentication as the original call, which is more efficient than making a full network call. If you are using different authentication or if you are invoking an endpoint from another API, make a network call using the 
SysUtility.rest<verb>()
 method.
 Example:
 
var custsJson = SysUtility.getResource("Customers", {filter: {"name like '%foo%' "}); var custs = JSON.parse(custsJson); for (var i = 0; i < custs.length; i++) { log.debug("Customer: " + JSON.stringify(custs[i])); }
Calls to your usual REST URL depend on your use of a load balancer. If you are using a load balancer, ensure that your load balancer sets HTTP forwarding headers properly.
For more information about these methods, see The SysUtility Object.
Call JavaScript Resources using GET and POST Requests
You can call JavaScript resources using GET and POST requests. Access the JSON payload with a POST using the 
req.json
 property in your JavaScript code. 
Layer7 Live API Creator
 performs logic on only table-based resources.
For more information:
Call Multiple HTTP Requests in Parallel
You can have 
Layer7 Live API Creator
 call multiple HTTP requests in parallel using the 
SysUtility.processHTTPInParallel()
 method in your JavaScript code. This method optimizes your API by creating separate threads to call the HTTP service requests, and then it returns and array of JSON responses. You can iterate through the responses to perform more processing or API mashups before returning the response to the client.
For more information about this method, including the syntax to use, see The SysUtility Object.