JavaScript

JavaScript
calac41
You can explore various JavaScript coding techniques that are relevant to defining business logic using JavaScript in 
CA Live API Creator
.
In this article:
CA Live API Creator
 and JavaScript
CA Live API Creator
 uses JavaScript as the scripting language for various reasons:
  • Keep things agile. You can simplify operations by loading and executing JavaScript code instead of compiling code into class files.
  • Avoid the pitfalls of JavaScript, such as async programming and lack of code completion. A hurdle for many application developers arises out of browser-based usage, where synchronous operations (reading a file or a database) can block the browser.
    JavaScript introduces the concept of asynchronous calls, with callbacks to process actual results. The following code snippet is an example from Rowan Manning's blog:
    console.log('First');
    jQuery.get('page.html', function (data) {
      console.log("Second"); // <--- this happens last
    });
    console.log('Third');
    As Rowan points out, the result is "First", "Third", "Second". This result is because 
    get
     is asynchronous, so execution proceeds past the
     
    statement (to "Third"). "Second" executes later, only when the 
    get
     call completes
    .
    JavaScript is an un-typed language. Code such as 
    var theValue = "some string"
     can be convenient, but you lose some services such as code completion in an integrated development environment. This service depends on typing information. 
    CA Live API Creator
     retains this capability for system objects.
    For more information about viewing a JavaScript tutorial, see the W3Schools JavaScript tutorial.
Server-side JavaScript is interoperable with Java. You can continue to leverage existing Java libraries and instantiate Java objects within the JavaScript code that you write in
CA Live API Creator
. Your server-side code, such as event rules, provides asynchronous event handling. Although JavaScript has a simple data structure notation,
CA Live API Creator
 supports rich data structure by using the JavaScript Object Notation (JSON) object. You can convert JavaScript values such as strings or JSON string to objects in your JavaScript code using the functions in this object.
 For more information about how to convert JavaScript values, see the "Using the JSON object" section.
CA Live API Creator
 uses JavaScript in the following contexts:
  • In the browser.
     Internally, 
    CA Live API Creator
     navigates the Document Object Model (DOM) (fields in a browser form) and handles event rules using JavaScript.
  • To create servers.
     
    CA Live API Creator
     uses Node.js for database access. Node.js provides a single language that covers the browser and the server. This server-side implementation of JavaScript is flexible, but low-level and complex.
  • As a scripting language for command-line scripting and scripting inside a virtual machine (VM). 
    You can build command language commands using JavaScript, in particular in Node.js. The JavaScript code can access Java code inside the JVM, including data sharing. This access provides the interpreted/un-typed simplicity of JavaScript with Java. Common implementations include Rhino and Nashorn.
JavaScript for Event Handling and Functions
CA Live API Creator
 employs JavaScript as a server-side scripting language in the API Server JVM. The JavaScript language provides the basic control flow and object access (for example, 
row.balance
) that is suitable for defining your logic in event rules and functions. 
Your JavaScript code has access to other code running in the JVM. API Server provides the threading functions, eliminating async issues within the JavaScript code that you define in API Creator's JavaScript code editor. You can use code completion for row variables in the JavaScript code editor. 
CA Live API Creator
knows the context of an event rule (for example, the event rule for 
customer
) and can therefore provide the 
customer
 attributes in a list from which you can select.
Use the JSON Object
In JavaScript, you can convert JavaScript values to and from their JSON string representation by using the JSON object:
myData = {name: "first", address: "california"};
myString = JSON.stringify(myData); // suitable for logging, send as API request/response data
myData2 = JSON.parse(myString); // get API response into JavaScript data
Consider a formula rule that has the 
row
 object in its JavaScript scope. You can convert the JavaScript value to a JSON string representation using the following code:
These functions do not support
CA Live API Creator
-specific objects, such as
row
and 
oldRow
, or other custom Java objects as arguments.
Example:
var stringifiedRow = JSON.
stringify(row)
; // stringifiedRow will always have the value '{}'
Instantiate JavaScript Objects
You can instantiate objects in JavaScript using the 
new
 operator. This usage is restricted to creating instances of user-defined JavaScript object types or of one of the built-in object types:
var variable-name = 
new
 constructor[([arguments])]
For example, instantiate a String type using the following syntax:
var variable-name = 
new
 String(“Your String here”);
Instantiate Java Objects Inside JavaScript
You can add Java libraries to your API by adding them to your 
classpath
. Your JavaScript code can access the Java classes that are defined in your Java libraries.
For more information about how to add a Java library to your API, see Logic Libraries.
Follow these steps:
  1. Access the 
    Class
     object from the Java libraries in the Java code using the following syntax: 
    var ClassObject = Java.type(“<full name of the Java class>”);
    Example:
    The following code snippet accesses the 
    org.bar.Foo
     Java class and uses the 
    Class
     object to call the 
    staticMethodOfFoo
     static method that is declared inside the 
    org.bar.Foo
     class:
    var Foo = Java.type(“org.bar.Foo”);
    Foo.staticMethodOfFoo(); 
  2. Instantiate the 
    Class
     object using the 
    new
     operator.
    Example:
    The following code snippet instantiates the 
    org.bar.Foo
     class in your JavaScript code and includes a non-parameterized constructor:
    var fooObject = new Foo(); 
    // Method calls.
    fooObject.instanceMethodOfFoo();
    Example:
    The following code snippet instantiates the 
    org.bar.Foo
     class in your JavaScript code and includes a parameterized constructor:
    var fooObject = new Foo(<parameter>); 
    // Method calls.
    fooObject.instanceMethodOfFoo();
The Java object is instantiated inside JavaScript.
 
Looping Examples
You can use the following code snippets to see how to use 
for...each
 in JavaScript code in API Creator.
for...each Loop Example
The following code snippet prints each array element for each 
(variable in object) {statement}
:
// for each (variable in object) { statement }
// print each array element
var arr = [ "hello", "world" ];
for each (a in arr) {
  print(a)
}
for...each Java Arrays Example
The following code snippet creates a ten-element 
int
 array, assigns squares, and prints values for each array element:
var JArray = Java.type("int[]");
// create 10 element int array
var arr = new JArray(10);
// assign squares
for (i in arr) {
  arr[i] = i*i;
}
// print values of each array element
for each (i in arr) {
  print(i);
for...each Java Map Example
The following code snippet prints all Java System property names and value pairs and prints all environment variables with values:
var System = Java.type("java.lang.System")
// print all Java System property name, value pairs 
for each (p in System.properties.entrySet()) {
  print(p.key, "=", p.value)
}
// print all environment variables with values
for each (e in System.env.entrySet()) {
  print(e.key, "=", e.value)
}
You can loop through related data using the following construct:
var worksForEmps = row.EmpsList; // get emps in dept row
for each (var eachEmp in worksForEmps) {
logicContext.logDebug(eachEmp);
}
JavaScript Coding Best Practices
The following JavaScript coding best practices are recommended when you write JavaScript code in API Creator:
Reserved JavaScript Context Variables
Do not use reserved JavaScript context variables as variable names. For example, the following code snippet sets reserved JavaScript context variables as variable names:
var 
row
 = null;
var 
oldRow
 = null;
var 
json
 = null;
var 
logicRequest
 = null;
For a list of the reserved JavaScript context variables, see Quick Reference.
Use JavaScript Library for Hard-Coded Variables
Instead of hard-coding values in your event rules and other rules, define a JavaScript library with all defined variables in that library. Then, complete the following:
  1. Add the library to your API.
  2. Define the library as available to JavaScript event programming and used in JavaScript logic by selecting the 
    Used 
    checkbox.
    Best Practice:
    Select this checkbox only for those JavaScript libraries that your API uses. There is CPU cost and memory associated with each library that you mark as 
    Used
    .
For more information about how to add a JavaScript library to your API, see Logic Libraries.
Use an Object to Contain Variables in JavaScript
In order to minimize the pollution of the top-level namespace where a number of variables are declared, you can define all the variables in one object. 
For example, the following code example is typical JavaScript variable declaration. You can access the variables from anywhere you define JavaScript code:
// These are the variables we use through the API
var serverURL = 'https://super.api.com/myAPI';
var filesLocation = '/opt/CA/stuff';
var maxNumOfThings = 42;
...
...
log.info("We are using URL : " + serverURL);