JavaScript Language-Specific Library

The JavaScript IC library provides a JavaScript implementation to communicate with IC servers via the REST interface. The library is largely a one-to-one pass-through to the REST service. It provides a collection of objects that represent resources and objects made available by the API. It abstracts away the work of performing low-level HTTP requests and packaging up data to send back and forth. With the JavaScript layer, you don’t have to know the exact URLs for things and it takes the guesswork out of supplying valid data objects since it enforces that for you.

This topic contains the following sections:

Overview

The library is provided as AMD, CommonJS, UMD, and global scope libraries. Each namespace from the REST API is provided as an individual module in the JavaScript API. Each module is made up of resources and data contracts, with the resources always being prefixed with a $. A resource will contain one or more functions, such as $connection.createConnection. The first parameter to the function will always be a parameter object that is an instance of the functionName.params type, such as $connection.createConnection.params. The second parameter is an object that is a map of HTTP response codes to callback functions.

On the result of the REST call, the library will perform a lookup into the response code map to find the appropriate function to call. In addition to containing a map of response codes, such as 200 or 404, the response map can also contain the following special keywords: ‘abort’, ‘timeout’, ‘error’, and ‘default’. There are multiple handlers possible for each scenario and the library will call the most specific handler possible. Any HTTP response codes will be the first handlers searched for. Otherwise ‘error’ will be tried for any 400 or 500 level code. During an aborted server call, ‘abort’ will be tried first followed by ‘error’. During a timeout scenario, ‘timeout’ will be tried first followed by ‘error’. In any scenario, if no other matching handler is found, ‘default’ will be attempted.

Connecting

The Connection and _util modules are used together to for a connection to an IC server. Prior to connecting _util’s setBaseUrl must be called to set what URL hosts the IC REST web service.

Connection modules $connection.createConnection creates a connection to an IC server. The createConnection.params’s ‘header’ property takes the requested language and ‘content’ property takes the BaseAuthConnectionRequestSettings derived object. This object will contain the essential connection parameters such as user name and password.

After creating a connection the station can be optionally set by using the Connection module and calling $station.changeStationConnection.

Messaging

The Messaging module is used to retrieve messages from the IC server. The messages are events that are raised on the IC server, such as a status changing or an interaction being added. If using short-polling, the messages are queued on the server and should be retrieved on a regular interval as the queue will start filling up again as soon as a batch of messages is retrieved. If using server-sent events, the messages are not queued on the server, and are sent as they occur. The client application should check the messaging feature version to determine if server-sent events is supported on the server. Server sent events are supported with messaging version 2 and higher. See the Versioning page for further information on handling versioning.

If using short-polling, calling $messages.getMessages will request the batch of messages from the server. The second parameter, callBacks, is an object that maps response codes (timeout, error, 200, 400, etc…) to functions. The appropriate function will be called based on the server’s response. If a 200 results, the second parameter to the callback will contain list of messages that were received. The array may be empty.

Putting It Together: Simple Examples

Asynchronous Module Definition (AMD) Example

Note

This example was written using the asynchronous module definition (AMD) pattern for loading dependencies. It utilizes the AMD ICWS JavaScript library and RequireJS. The RequireJS JavaScript library will need to be obtained and included since is not distributed with the AMD ICWS JavaScript library. Alternative loaders, such as Dojo and Almond could be used in its place if desired.

<script type='text/javascript' src='require.js'></script>
            
require(['_util', 'messaging', 'connection'], function(_util, messaging, connection){
    // Set the base url so the library knows how to map its server calls
    _util.setBaseUrl('https://HostServerName:HostPort');
    
    // Variable to hold an EventSource instance in case server-sent events is supported.
    var eventSource;
    
    // Setup some connection parameters
    var connectionParams = new connection.IcAuthConnectionRequestSettings();
    
    connectionParams.applicationName = 'Example';
    connectionParams.userID = 'username';
    connectionParams.password = 'password';
    
    // Connect to the IC server
    connection.$connection.createConnection(
        new connection.$connection.createConnection.params(
            {
                header: {
                    'Accept-Language': "en-US",
                },
                content: connectionParams,
                // Setting the include query parameter to features so that
                // the list of IC Server feature versions are available on
                // the 201 connection response.
                query: { 'include': 'features' },
            }),
            // The second parameter is a map of callbacks to execute based on the server response
            {
                '201': function (xhr, connectionResponse) {
                    // A 201 represents a successful connection, connectionResponse.alternateHostList are the paths 
                    // to alternate servers.
                    
                    var messagingVersion = 0;
                    
                    // Store the messaging version, for use in determining if short-polling or 
                    // server-sent events should be used.
                    if (connectionResponse.features) {
                        for (var i = connectionResponse.features.length - 1; i >= 0; i--) {
                            var featureObject = connectionResponse.features[i];

                            if (featureObject.featureId === 'messaging') {
                                messagingVersion = featureObject.version;
                                break;
                            }
                        }
                    }
                                            
                    // We can now set our station
                    var workstationSettings = new connection.WorkstationSettings();
                    
                    workstationSettings.workstation = 'ExampleStation';
                    
                    var stationParams = new connection.$station.changeStationConnection.params(
                        {
                            content:  workstationSettings
                        });
                    
                    connection.$station.changeStationConnection(stationParams,
                    {
                        '200': function(xhr, changeStationResponse) {
                            // Omitted:  TODO, handle any post change station actions.
                        },
                        '401': handleChangeStationError,
                        'timeout': handleChangeStationError,
                        'default': handleChangeStationError,
                        'error': handleChangeStationError,
                    });
                    
                    // Start message processing
                    startMessageProcessing(messagingVersion);
                },
                '401': handleConnectionError,
                'timeout': handleConnectionError,
                'default': handleConnectionError,
                'error': handleConnectionError,
            });
            
    function handleConnectionError(xhr) {
        // Omitted:  TODO, handle xhr.status / xhr.response
    }
    
    function handleChangeStationError(xhr) {
        // Omitted:  TODO, handle xhr.status / xhr.response
    }
            
    function startMessageProcessing(messagingVersion) {
        // Check to see if the IC Server and the browser supports server-sent events.
        if (messagingVersion >= 2 && typeof EventSource !== 'undefined') {
            startServerSentEventsMessageProcessing();
        } else {
            startShortPollingMessageProcessing();
        }
    }
    
    function startShortPollingMessageProcessing() {
        // Poll the server of any events that have occurred.  This should be expected
        // on a regular interval
        
        // TODO:  This example does not show putting this call in an interval
        
        messaging.$messages.getMessages(
            new messaging.$messages.getMessages.params({}),
                // The second parameter is a map of callbacks to execute based on the server response
                {
                    '200': function (xhr, messages) {
                        // messages contains an array of server side events that were retrieved
                        for (var i = messages.length - 1; i >= 0; i--) {
                            var message = messages[i];
                            handleMessage(message);
                        };
                    },

                    '401': handleMessageError,
                    'timeout': handleMessageError,
                    'default': handleMessageError,
                    'error': handleMessageError,
                });
    }
    
    function startServerSentEventsMessageProcessing() {
        if (!eventSource) {
            var parameters = new Messaging.$messages.EventSource.params({});
            
            eventSource = new Messaging.$messages.EventSource(parameters, { message: handleMessage });
        };
    }
    
    function handleMessageError(xhr) {
        // Omitted:  TODO, handle xhr.status / xhr.response
    }
    
    function handleMessage(message) {
        // Omitted:  TODO, handle message
    }
});
                            

Back to top

Universal Module Definition (UMD) Example

Note

This example was written using the universal module definition (UMD) pattern for loading dependencies. It utilizes the UMD ICWS JavaScript library and RequireJS. The RequireJS JavaScript library will need to be obtained and included since is not distributed with the UMD ICWS JavaScript library. Alternative loaders, such as Dojo and Almond could be used in its place if desired.

            
(function (root, factory) {
if (typeof exports === 'object') {
    factory(exports, require('./_util'), require('./messaging'), require('./connection'));
} else if (typeof define === 'function' && define.amd) {
    define(['exports', './_util', './messaging', './connection'], factory);
} else {
    (function(parent) {
        var namespaces = ['ININ','ICWS','Common'], childName;
        while (childName = namespaces.shift()) {
            if (!parent[childName]) {
                parent = parent[childName] = {};
            } else {
                parent = parent[childName];
            }
        }
    }(root));
    factory(root.ININ.ICWS.Common, root.ININ.ICWS._util, root.ININ.ICWS.messaging, root.ININ.ICWS.connection);
}(this, function (exports, _util, messaging, connection) {
    // Set the base url so the library knows how to map its server calls
    _util.setBaseUrl('https://HostServerName:HostPort');
    
    // Variable to hold an EventSource instance in case server-sent events is supported.
    var eventSource;
    
    // Setup some connection parameters
    var connectionParams = new connection.IcAuthConnectionRequestSettings();
    
    connectionParams.applicationName = 'Example';
    connectionParams.userID = 'username';
    connectionParams.password = 'password';
    
    // Connect to the IC server
    connection.$connection.createConnection(
        new connection.$connection.createConnection.params(
            {
                header: {
                    'Accept-Language': "en-US",
                },
                content: connectionParams,
                // Setting the include query parameter to features so that
                // the list of IC Server feature versions are available on
                // the 201 connection response.
                query: { 'include': 'features' },
            }),
            // The second parameter is a map of callbacks to execute based on the server response
            {
                '201': function (xhr, connectionResponse) {
                    // A 201 represents a successful connection, connectionResponse.alternateHostList are the paths 
                    // to alternate servers.
                    
                    var messagingVersion = 0;
                    
                    // Store the messaging version, for use in determining if short-polling or 
                    // server-sent events should be used.
                    if (connectionResponse.features) {
                        for (var i = connectionResponse.features.length - 1; i >= 0; i--) {
                            var featureObject = connectionResponse.features[i];

                            if (featureObject.featureId === 'messaging') {
                                messagingVersion = featureObject.version;
                                break;
                            }
                        }
                    }
                                            
                    // We can now set our station
                    var workstationSettings = new connection.WorkstationSettings();
                    
                    workstationSettings.workstation = 'ExampleStation';
                    
                    var stationParams = new connection.$station.changeStationConnection.params(
                        {
                            content:  workstationSettings
                        });
                    
                    connection.$station.changeStationConnection(stationParams,
                    {
                        '200': function(xhr, changeStationResponse) {
                            // Omitted:  TODO, handle any post change station actions.
                        },
                        '401': handleChangeStationError,
                        'timeout': handleChangeStationError,
                        'default': handleChangeStationError,
                        'error': handleChangeStationError,
                    });
                    
                    // Start message processing
                    startMessageProcessing(messagingVersion);
                },
                '401': handleConnectionError,
                'timeout': handleConnectionError,
                'default': handleConnectionError,
                'error': handleConnectionError,
            });
            
    function handleConnectionError(xhr) {
        // Omitted:  TODO, handle xhr.status / xhr.response
    }
    
    function handleChangeStationError(xhr) {
        // Omitted:  TODO, handle xhr.status / xhr.response
    }
            
    function startMessageProcessing(messagingVersion) {
        // Check to see if the IC Server and the browser supports server-sent events.
        if (messagingVersion >= 2 && typeof EventSource !== 'undefined') {
            startServerSentEventsMessageProcessing();
        } else {
            startShortPollingMessageProcessing();
        }
    }
    
    function startShortPollingMessageProcessing() {
        // Poll the server of any events that have occurred.  This should be expected
        // on a regular interval
        
        // TODO:  This example does not show putting this call in an interval
        
        messaging.$messages.getMessages(
            new messaging.$messages.getMessages.params({}),
                // The second parameter is a map of callbacks to execute based on the server response
                {
                    '200': function (xhr, messages) {
                        // messages contains an array of server side events that were retrieved
                        for (var i = messages.length - 1; i >= 0; i--) {
                            var message = messages[i];
                            handleMessage(message);
                        };
                    },

                    '401': handleMessageError,
                    'timeout': handleMessageError,
                    'default': handleMessageError,
                    'error': handleMessageError,
                });
    }
    
    function startServerSentEventsMessageProcessing() {
        if (!eventSource) {
            var parameters = new Messaging.$messages.EventSource.params({});
            
            eventSource = new Messaging.$messages.EventSource(parameters, { message: handleMessage });
        };
    }
    
    function handleMessageError(xhr) {
        // Omitted:  TODO, handle xhr.status / xhr.response
    }
    
    function handleMessage(message) {
        // Omitted:  TODO, handle message
    }
});
                            

Back to top

CommonJS Example

Note

This example was written using the CommonJS pattern for loading dependencies. It utilizes the CommonJS ICWS JavaScript library and RequireJS. The RequireJS JavaScript library will need to be obtained and included since is not distributed with the CommonJS ICWS JavaScript library. Alternative loaders, such as Dojo and Almond could be used in its place if desired.

            
var _util = require('_util'),
messaging = require('messaging'),
connection = require('connection');

// Set the base url so the library knows how to map its server calls
_util.setBaseUrl('https://HostServerName:HostPort');

// Variable to hold an EventSource instance in case server-sent events is supported.
var eventSource;

// Setup some connection parameters
var connectionParams = new connection.IcAuthConnectionRequestSettings();

connectionParams.applicationName = 'Example';
connectionParams.userID = 'username';
connectionParams.password = 'password';

// Connect to the IC server
connection.$connection.createConnection(
    new connection.$connection.createConnection.params(
        {
            header: {
                'Accept-Language': "en-US",
            },
            content: connectionParams,
            // Setting the include query parameter to features so that
            // the list of IC Server feature versions are available on
            // the 201 connection response.
            query: { 'include': 'features' },
        }),
        // The second parameter is a map of callbacks to execute based on the server response
        {
            '201': function (xhr, connectionResponse) {
                // A 201 represents a successful connection, connectionResponse.alternateHostList are the paths 
                // to alternate servers.
                
                var messagingVersion = 0;
                
                // Store the messaging version, for use in determining if short-polling or 
                // server-sent events should be used.
                if (connectionResponse.features) {
                    for (var i = connectionResponse.features.length - 1; i >= 0; i--) {
                        var featureObject = connectionResponse.features[i];

                        if (featureObject.featureId === 'messaging') {
                            messagingVersion = featureObject.version;
                            break;
                        }
                    }
                }
                                        
                // We can now set our station
                var workstationSettings = new connection.WorkstationSettings();
                
                workstationSettings.workstation = 'ExampleStation';
                
                var stationParams = new connection.$station.changeStationConnection.params(
                    {
                        content:  workstationSettings
                    });
                
                connection.$station.changeStationConnection(stationParams,
                {
                    '200': function(xhr, changeStationResponse) {
                        // Omitted:  TODO, handle any post change station actions.
                    },
                    '401': handleChangeStationError,
                    'timeout': handleChangeStationError,
                    'default': handleChangeStationError,
                    'error': handleChangeStationError,
                });
                
                // Start message processing
                startMessageProcessing(messagingVersion);
            },
            '401': handleConnectionError,
            'timeout': handleConnectionError,
            'default': handleConnectionError,
            'error': handleConnectionError,
        });
        
function handleConnectionError(xhr) {
    // Omitted:  TODO, handle xhr.status / xhr.response
}

function handleChangeStationError(xhr) {
    // Omitted:  TODO, handle xhr.status / xhr.response
}
        
function startMessageProcessing(messagingVersion) {
    // Check to see if the IC Server and the browser supports server-sent events.
    if (messagingVersion >= 2 && typeof EventSource !== 'undefined') {
        startServerSentEventsMessageProcessing();
    } else {
        startShortPollingMessageProcessing();
    }
}

function startShortPollingMessageProcessing() {
    // Poll the server of any events that have occurred.  This should be expected
    // on a regular interval
    
    // TODO:  This example does not show putting this call in an interval
    
    messaging.$messages.getMessages(
        new messaging.$messages.getMessages.params({}),
            // The second parameter is a map of callbacks to execute based on the server response
            {
                '200': function (xhr, messages) {
                    // messages contains an array of server side events that were retrieved
                    for (var i = messages.length - 1; i >= 0; i--) {
                        var message = messages[i];
                        handleMessage(message);
                    };
                },

                '401': handleMessageError,
                'timeout': handleMessageError,
                'default': handleMessageError,
                'error': handleMessageError,
            });
}

function startServerSentEventsMessageProcessing() {
    if (!eventSource) {
        var parameters = new Messaging.$messages.EventSource.params({});
        
        eventSource = new Messaging.$messages.EventSource(parameters, { message: handleMessage });
    };
}

function handleMessageError(xhr) {
    // Omitted:  TODO, handle xhr.status / xhr.response
}

function handleMessage(message) {
    // Omitted:  TODO, handle message
}
                            

Back to top

Global Scope Example

Note

This example was written using the CommonJS pattern for loading dependencies. It utilizes the Global Scope ICWS JavaScript library and RequireJS. The RequireJS JavaScript library will need to be obtained and included since is not distributed with the Global Scope ICWS JavaScript library. Alternative loaders, such as Dojo and Almond could be used in its place if desired.


(function(root){

    var _util = root.ININ.ICWS._util;
    var messaging = root.ININ.ICWS.messaging;
    var connection = root.ININ.ICWS.connection;
            
    // Set the base url so the library knows how to map its server calls
    _util.setBaseUrl('https://HostServerName:HostPort');
    
    // Variable to hold an EventSource instance in case server-sent events is supported.
    var eventSource;
    
    // Setup some connection parameters
    var connectionParams = new connection.IcAuthConnectionRequestSettings();
    
    connectionParams.applicationName = 'Example';
    connectionParams.userID = 'username';
    connectionParams.password = 'password';
    
    // Connect to the IC server
    connection.$connection.createConnection(
        new connection.$connection.createConnection.params(
            {
                header: {
                    'Accept-Language': "en-US",
                },
                content: connectionParams,
                // Setting the include query parameter to features so that
                // the list of IC Server feature versions are available on
                // the 201 connection response.
                query: { 'include': 'features' },
            }),
            // The second parameter is a map of callbacks to execute based on the server response
            {
                '201': function (xhr, connectionResponse) {
                    // A 201 represents a successful connection, connectionResponse.alternateHostList are the paths 
                    // to alternate servers.
                    
                    var messagingVersion = 0;
                    
                    // Store the messaging version, for use in determining if short-polling or 
                    // server-sent events should be used.
                    if (connectionResponse.features) {
                        for (var i = connectionResponse.features.length - 1; i >= 0; i--) {
                            var featureObject = connectionResponse.features[i];

                            if (featureObject.featureId === 'messaging') {
                                messagingVersion = featureObject.version;
                                break;
                            }
                        }
                    }
                                            
                    // We can now set our station
                    var workstationSettings = new connection.WorkstationSettings();
                    
                    workstationSettings.workstation = 'ExampleStation';
                    
                    var stationParams = new connection.$station.changeStationConnection.params(
                        {
                            content:  workstationSettings
                        });
                    
                    connection.$station.changeStationConnection(stationParams,
                    {
                        '200': function(xhr, changeStationResponse) {
                            // Omitted:  TODO, handle any post change station actions.
                        },
                        '401': handleChangeStationError,
                        'timeout': handleChangeStationError,
                        'default': handleChangeStationError,
                        'error': handleChangeStationError,
                    });
                    
                    // Start message processing
                    startMessageProcessing(messagingVersion);
                },
                '401': handleConnectionError,
                'timeout': handleConnectionError,
                'default': handleConnectionError,
                'error': handleConnectionError,
            });
            
    function handleConnectionError(xhr) {
        // Omitted:  TODO, handle xhr.status / xhr.response
    }
    
    function handleChangeStationError(xhr) {
        // Omitted:  TODO, handle xhr.status / xhr.response
    }
            
    function startMessageProcessing(messagingVersion) {
        // Check to see if the IC Server and the browser supports server-sent events.
        if (messagingVersion >= 2 && typeof EventSource !== 'undefined') {
            startServerSentEventsMessageProcessing();
        } else {
            startShortPollingMessageProcessing();
        }
    }
    
    function startShortPollingMessageProcessing() {
        // Poll the server of any events that have occurred.  This should be expected
        // on a regular interval
        
        // TODO:  This example does not show putting this call in an interval
        
        messaging.$messages.getMessages(
            new messaging.$messages.getMessages.params({}),
                // The second parameter is a map of callbacks to execute based on the server response
                {
                    '200': function (xhr, messages) {
                        // messages contains an array of server side events that were retrieved
                        for (var i = messages.length - 1; i >= 0; i--) {
                            var message = messages[i];
                            handleMessage(message);
                        };
                    },

                    '401': handleMessageError,
                    'timeout': handleMessageError,
                    'default': handleMessageError,
                    'error': handleMessageError,
                });
    }
    
    function startServerSentEventsMessageProcessing() {
        if (!eventSource) {
            var parameters = new Messaging.$messages.EventSource.params({});
            
            eventSource = new Messaging.$messages.EventSource(parameters, { message: handleMessage });
        };
    }
    
    function handleMessageError(xhr) {
        // Omitted:  TODO, handle xhr.status / xhr.response
    }
    
    function handleMessage(message) {
        // Omitted:  TODO, handle message
    }
})();
                            

Back to top