Developing APIs‎ > ‎

JavaScript

As an application developer experienced in languages such as Java or C#, but new to JavaScript, you want to use API Creator and explore the various elements of JavaScript that are relevant to using API Creator.

Live API Creator and JavaScript

API Creator uses JavaScript as a well-known and popular language to:

  • Keep things agile. You can load and execute JavaScript code from text files and databases, which simplifies operations. You do not need to compile into class files.
  • Avoid pitfalls of JavaScript, such as async programming and lack of code completion. Perhaps the biggest 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". That's 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. You will see code like var theValue = "some string". This can can be convenient, but you lose some services such as code completion in an integrated development environment which depend on typing information. API Creator retains this capability for system objects.

  • Retain the use of existing software running in the Java virtual machine (JVM). This server-side JavaScript is interoperable with Java (can call, be called by). You can instantiate Java objects in JavaScript.

You can server-side code, such as events, using API Creator, which provides asynchronous event handling.

    • Execute your JavaScript code in browsers and on servers using the Nashorn JavaScript engine. While initial JavaScript use was in the browser, it is now commonly accepted as a server language.
    • Support its data structure. One of the beauties of JavaScript is its simple data structure notation, which lead to its adoption as a data interchange format for RESTful APIs. The JSON class provides functions to convert strings to objects, for example:
    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

    API Creator uses JavaScript in the following contexts:

    • In the browser. Internally, API Creator navigates the Document Object Model (DOM) (fields in a browser form) and handles events using JavaScript (AngularJS).
    • To create servers. API Creator uses Node.js for database access. Node.js provides a single language covering both the browser and the server. It is flexible, but low-level and complex.
    • As a scripting language. For:
      • Command line scripting. You can build new command language commands using JavaScript, in particular in Node.js.
      • Scripting inside a virtual machine (VM). It is increasingly common to use server-side JavaScript inside a JVM. The JavaScript code can access Java code inside the JVM, including data sharing. This provides the interpreted/un-typed simplicity of JavaScript in conjunction with Java. Common implementations include Rhino and Nashorn.

    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.

    JavaScript Tooling

    The following tooling is built around JavaScript:
    • Browser tools to debug JavaScript. Most browsers provide tools to debug JavaScript. The following are common packages:
      • jQuery. Simplifies DOM access.
      • AngularJS. Provides a model-view-controller (MVC) framework for building applications. 
    • Node.js. The following Node.js elements are useful to Live API Creator:
      • Node.js for command languages. Node packages can include information that make their functionality available in command lines. The Admin command line interface (CLI) uses the Node packages.
      • Node.js installation.
        For more information about installing Node.js, see Install NodeJS.
      • Node.js Node Package Manager (npm). Node.js has simplified installing packages with the conventions around npm. This is a node-based command extension that installs the designated package.

    JavaScript for Event Handling and Functions

    API Creator employs JavaScript for event handling and functions, since JavaScript is a popular language used in virtually all systems. Consequently, most programmers have some familiarity with it. JavaScript's interpretive nature is suitable for no-compile/no-deploy API creation and provides the basic control flow and object access (for example, row.balance) that is required.

    In the context of short event handlers, the un-typed nature of JavaScript is less of an issue. It provides features often not found for JavaScript coding, such as code completion for system objects.

    Live API Creator employs JavaScript as a server-side scripting language in the API Server JVM. Your JavaScript has access to other code running in the JVM. API Server provides the threading functions, eliminating async issues. 

    You can write simple loops to process results, and they run in the expected (synchronous) order. The API Creator JavaScript code editor provides code completion services for row variables. API Creator knows the context of a logic event (for example, the event for customer) and can therefore provide the customer attributes in a list you can select from.

    How to Use the JSON Object

    In JavaScript, you can convert JavaScript values to and from their JSON string representation by invoking the following JSON object functions:

    • stringify(<value>)
    • parse(<JSON string>)
    Note: These functions do not support Live API Creator-specific objects (like row, oldRow) or other custom Java objects as arguments.

    Example:

    Consider a formula rule that has the row object in its JavaScript scope. You can convert the JavaScript value to a JSON string representation by executing the following code:

    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 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 defined in your Java libraries using syntax.

    For more information about how to add Java user libraries to Live API Creator, see Logic Libraries.

    1. Access the Class object from Java user 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 Java class org.bar.Foo Java class and uses the Class object to call the staticMethodOfFoo static method 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 Java 
      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 Java org.bar.Foo class in your JavaScript code and includes a parameterized constructor:

    var fooObject = new Foo(<parameter>); 
    // Method calls.
    fooObject.instanceMethodOfFoo();

    Looping Examples

    The following code snippets are examples showing how you can use for...each in JavaScript in Live 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);
    }
    Subpages (1): Code Completion