JavaScript Client API

powerful. fast. easy.

The AMPS JavaScript Client lets you write cross-platform messaging applications for both web apps working in a browser, as well as server-side applications that use Node.js. It uses the power of WebSocket technology combined with asyncronous nature of JavaScript.

Quick Start

Once the client is downloaded, it can be used in your JavaScript/TypeScript projects:

Node.js
1 const { Client } = require('amps');
2 console.log(Client.version());

TypeScript / ES6
 1 // NPM installation: Import everything at once
 2 import * as amps from 'amps';
 3 console.log(amps.Client.version());
 4 
 5 // or
 6 
 7 // NPM installation: This way the final bundle can be smaller
 8 import { Client, Command } from 'amps';
 9 console.log(Client.version());
10 
11 // Manual installation (don't forget to add a typing reference):
12 /// <reference path="./amps.d.ts" />
13 import * as amps from './amps';
14 import { Client, Command } from './amps';

Application That Uses AMD Modules
1 define(['dist/amps'], amps => {
2     console.log(amps.Client.version());
3 });

Global Import in Browsers
1 <!-- Optional import, support for obsolete browsers like IE11 -->
2 <script src="es6-promise.min.js"></script>
3 <script src="amps.js"></script>

You are now ready to use AMPS in your project!

Here are a few JavaScript examples to get you started:

Example 1: Connect and Subscribe

In this example, we connect to an AMPS server running locally and initiate a subscription to the orders topic.

 1 import { Client } from 'amps';
 2 
 3 
 4 (async () => {
 5   const client = new Client('my-application');
 6 
 7   try {
 8     await client.connect('ws://localhost:9100/amps/json');
 9 
10     // Connected, let's subscribe to a topic now
11     const subscriptionId = await client.subscribe(
12         message => console.log(message.data),
13         'orders'
14     );
15 
16     // Once we subscribed, the subscriptionId is returned
17     console.log(subscriptionId);
18 
19     client.publish('orders', {order: 'Tesla 3', qty: 10});
20   }
21   catch (err) {
22     // This can be either a connection error or a subscription error
23     console.log(err);
24   }
25 })();

As new orders are posted, the message handler is invoked with each message, and prints the data of each order to the console:

 1 const onMessage = message => console.log('message: ', message);
 2 
 3 // ... in asynchronous context
 4 try {
 5   // subscribe for the first topic
 6   await client.subscribe(onMessage, 'orders');
 7 
 8   // second subscription
 9   await client.subscribe(onMessage, 'reservations');
10 
11   // third subscription
12   await client.subscribe(onMessage, 'notifications');
13 }
14 catch (err) {
15   // if any subscription failed, the error will end up here
16   console.error('subscription error:', err);
17 }
Since every command (except publish()) is asynchronous and returns a Promise object, it is very easy to chain commands and handle errors.

Example 2: Publish a Message

With AMPS, publishing is simple, as shown in this example. We connect to an AMPS server running locally, and publish a single message to the messages topic. To simply publish a message, there is no need to predeclare the topic or configure complex routing. Any subscription that has asked for XML messages on the messages topic will receive the message.

1 // ... in asynchronous context
2 try {
3   const client = new Client('publish-example');
4   await client.connect('ws://localhost:9100/amps/xml');
5   client.publish('messages', '<hi>Hello, world!</hi>');
6 }
7 catch (err) {
8   console.log(err);
9 }

Example 3: Disconnect Handling

In this example, we need to be subscribed to the orders topic, even if connectivity to our AMPS server is temporarily interrupted. We use a reconnect function to enable recovery from a connection error. When AMPS detects a connection error, the reconnect function is called from errorHandler to re-establish connection, and then subscribes to the topic again once a successful connection is made. Notice that the errorHandler is only called after a successful connection has been established, otherwise a connection error is caught by the catch callback of the connect Promise.

 1 import { Client } from 'amps';
 2 
 3 
 4 // simple sleep/pause async function
 5 const sleep = interval => new Promise(
 6     resolve => setTimeout(resolve, interval)
 7 );
 8 
 9 // Assign an error handler that will handle general error 
10 // such as disconnects
11 const client = new Client('my-app').errorHandler(async err => {
12     // Error handler is only called if an error occurred after
13     // a successful connection has been established.
14     client.disconnect();
15 
16     // wait for 5 seconds before attempting to connect
17     console.error(err, 'Reconnecting after 5 seconds...');
18     await sleep(5000);
19 
20     reconnect();
21 });
22 
23 async function reconnect() {
24     try {
25       await client.connect('wss://localhost:9100/amps/json');
26 
27       // connected, let's subscribe
28       try {
29           await client.subscribe(
30               message => console.log('message: ', message),
31               'orders'
32           );
33       }
34       catch (err) {
35         console.error('Subscription error: ', err);
36       }
37     }
38     catch (err) {
39       console.error('Connection error: ', err);
40       await sleep(5000);
41       reconnect();
42     }
43 }
44 
45 // Begin by connecting and subscribing
46 reconnect();

Example 4: Query the Contents of a State-of-the-World Topic

State-of-the-World ("SOW") topics in AMPS combine the power of a database table with the performance of a publish-subscribe system. Use the AMPS JavaScript client to query the contents of a SOW topic.

 1 // ... in asynchronous context
 2 try {
 3   const client = new Client('my-application');
 4   await client.connect('ws://localhost:9100/amps/json');
 5   await client.sow(
 6       message => {
 7         if (message.header.command() == 'sow') {
 8             console.log(message.data);
 9         }
10       },
11       'orders',
12       "/symbol='ROL'",
13       {
14           batchSize: 100,
15           timeout: 5000
16       }
17   );
18 }
19 catch (err) {
20   console.error('Error: ', err);
21 }

This example queries for all orders for the symbol ROL, and simply prints the messages to the console.

Example 5: Command Interface

Even though AMPS clients provide the above named convenience methods for core AMPS functionality, you can use the Command object to customize the messages that AMPS sends. This is useful for more advanced scenarios where you need precise control over the message, or in cases where you need to use an earlier version of the client to communicate with a more recent version of AMPS, or in cases where a named method is not available.

 1 // ... in asynchronous context
 2 try {
 3   const client = new Client('my-application');
 4   await client.connect('ws://localhost:9100/amps/json')
 5 
 6   const subCmd = new Command('subscribe')
 7                      .topic('messages')
 8                      .filter('/id > 20');
 9 
10   await client.execute(
11       subCmd, 
12       message => console.log('message: ', message.data)
13   );
14 }
15 catch (err) {
16   console.error('Error: ', err);
17 }

This example provides the subscription to a messages topic with a filter applied.

AMPS Server Configuration for Websockets

To configure AMPS for Websocket support, you need to specify the following Transport:

1 <Transports>
2     <Transport>
3         <Name>json-websocket</Name>
4         <Type>tcp</Type>
5         <Protocol>websocket</Protocol>
6         <InetAddr>9100</InetAddr>
7         <MessageType>json</MessageType>
8     </Transport>
9 </Transports>

With the above configuration, AMPS will listen for incoming Websocket connections on port 9100 and will support the json message type. To use TLS/SSL, you'd specify a Certificate and PrivateKey (and optionally the Ciphers):

 1 <Transport>
 2     <Name>json-websocket-secure</Name>
 3     <Type>tcp</Type>
 4     <Protocol>websocket</Protocol>
 5     <InetAddr>9443</InetAddr>
 6     <MessageType>json</MessageType>
 7     <Certificate>./cert.pem</Certificate>
 8     <PrivateKey>./key.pem</PrivateKey>
 9     <Ciphers>HIGH:!aNULL:!MD5:@STRENGTH</Ciphers>
10 </Transport>

Authentication

AMPS provides an option for websocket protocol that controls authentication: WWWAuthenticate. This option provides a flexible way of setting up authorization for the JavaScript client.

The option can have the following values:

  • Negotiate (Kerberos)
  • NTLM
  • Basic realm="Secure Area"

When using Negotiate or NTLM, you don't have to do anything from the JavaScript client: authentication is automatically handled by browser/environment. When using Basic Auth (we recommend using wss in this scenario), you'll need to set a URI of the form wss://user:password@ip:port/amps/json.

By default, no authentication is performed until the 'logon' command is performed after connection.

In order to enable authentication for the AMPS JavaScript client, you need to specify the following settings:

  1. Add a protocol in the Protocols section of the config:
     1 <Protocol>
     2     <Name>websocket-portal</Name>
     3     <Module>websocket</Module>
     4     <!-- Basic Auth -->
     5     <WWWAuthenticate>Basic realm="Secure Area"</WWWAuthenticate>
     6     <!-- Kerberos-->
     7     <WWWAuthenticate>Negotiate</WWWAuthenticate>
     8     <!-- NTLM -->
     9     <WWWAuthenticate>NTLM</WWWAuthenticate>
    10 </Protocol>
  2. Specify a transport in the Transports section of the config that will be used for the JavaScript client:
    1 <Transport>
    2     <Name>websocket-auth</Name>
    3     <Type>tcp</Type>
    4     <Protocol>websocket-portal</Protocol>
    5     <InetAddr>9002</InetAddr>
    6 </Transport>

Everything You Need

If you need more help getting started, the 60East Technologies support and services team is ready to provide the support you need to help you CRANK UP THE AMPS.

The current release of the JavaScript client is version 5.3.2.0, which supports AMPS servers version 5.2 and later.