Define JavaScript Resource Types

Define JavaScript Resource Types
lac31
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. The 
CustomerJSOrdersREST
 resource in the Demo API is an example that illustrates how you can deliver JSON results combining managed data (
Customers
) with external service results (
Orders
) by retrieving resource information from another REST server (Sample) as the data for the 
OrdersRest
 sub-resource.
In this article:
The following code snippet shows the JavaScript sub-resource code:
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);
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/rest/default/demo/v1/CustomerJSOrdersREST/Alpha%20and%20Sons",
    "checksum": "A:e86aea2e0a4e74bf"
  },
  "OrdersRest": [
    {
      "ident":11,
      "amount_total":50,
      "amount_discounted":50,
      "amount_paid":0,
      "amount_un_paid":50,
      "is_ready":false,
      "approving_officer":"G PO.1",
      "officer_item_usage_approval":"",
      "unresolved_usage_count":0,
      "placed_date":"2013-11-01",
      "due_date":"2013-12-01",
      "salesrep_name":"A. Lincoln",
      "customer_name":"Alpha and Sons",
      "cloned_from_order_ident":0,
      "item_count":2,
      "empsales_year":null,
      "empsales_month":null,
      "@metadata":{
        "href":"http://localhost:8080/rest/default/sample/v1/sample:orders/11",
        "checksum":"A:70de9cd99c0b86ef",
        "links":[
          {
            "href":"http://localhost:8080/rest/default/sample/v1/sample:payment_order_allocations?sysfilter=equal('order_ident':11)",
            "rel":"children",
            "role":"payment_order_allocationsList",
            "type":"urn:caliveapicreator:examples:sample:sample:payment_order_allocations"
          },
     {
     "href":"http://localhost:8080/rest/default/sample/v1/sample:lineitem_usages?sysfilter=equal('order_ident':11)",
     "rel":"children",
     "role":"lineitem_usagesList",
....
...
...
]
Context
As shown in this example, your code has pre-supplied context for:
  • containingRow
    . You can access data from the containing row, here a Customer row from the
    CustomerJSOrdersREST
     containing resource. You can "parameterize" the call to the external service to get the data for the sub-resource by using attributes from the 
    containingRow.
  • log
    . For debugging. You can view debugging information in the log.
    For more information about the log, see View Logging Information.
  • SysUtility.restGet
    . You can use this to invoke REST services.
  • req
    . This object has the following 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, // May 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 context variables that are set when
CA Live API Creator
invokes JavaScript logic, see the Quick Reference.
Usage
CA 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. It cannot supply advanced automation services such as pagination or update.
Calling Local Services
If you are making calls to a local service (for instance, an APICreator REST service on the same server), use 
SysUtility.getResource
 instead of making a full network call.
For 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]));
}
This is more efficient, and it uses the same authentication as the original call. If you need to use different authentication, make a network call.
Depending on whether you are using a load balancer or not, a call to your usual REST URL may or may not work. You may have to make a call to localhost, port 8080, instead.