Your First AMPS Program

In this chapter, we will learn more about the structure and features of the AMPS JavaScript client and build our first JavaScript program using AMPS.

About the Client Library

The AMPS client library is packaged as a single file, amps.js in development environments, or amps.min.js for production. Every JavaScript application you build will need to reference this file, and the file must be deployed along with your application in order for your application to function properly. Alternatively, for applications that are distributed through NPM, the client library can be listed as a dependency, and thus installed automatically.

Including the Client in a Project

There are several ways of including the JavaScript client in order to use it. Depending on your project's structure and environment, you can include the client in one of the following ways.

Node.js / CommonJS Module

// NPM installation: Import everything at once
const amps = require('amps');

// or

// NPM installation: Include only selected components of AMPS
const { Client, Command } = import('amps');

// Same as above with manual installation
const amps = require('./lib/amps');
const { Client, Command } = import('./lib/amps');

ES6 / TypeScript Module

// NPM installation
import { Client, Command } from 'amps';

// Manual installation
import { Client, Command } from './lib/amps';

In case of TypeScript and manual installation, you need to reference the typing file (provided within the client package) at the top of the file:

/// <reference path="./lib/amps.d.ts" />
import { Client, Command } from './lib/amps';

The AMPS JavaScript NPM package already includes typings, so that the library can be seamlessly used in native TypeScript projects.

AMD / RequireJS Module

// Included library will be available as the amps argument
define(['./lib/amps'], amps => {
    // ...
});

Global Import in a Browser Environment

<!-- Optional import, to support obsolete browsers like IE11 -->
<script src="/lib/es6-promise.min.js"></script>
<script src="/lib/amps.js"></script>

Once the library in included in the HTML file, it becomes available as a global object, either as amps or window.amps.

Connecting to AMPS

Let's begin by writing a simple program that connects to an AMPS server and sends a single message to a topic. This code will be covered in detail just following the example.

const uri = 'wss://127.0.0.1:9007/amps/json';

async function main() {
    const client = new Client('examplePublisher');

try {
    await client.connect(uri);
    client.publish('messages', {hi: 'Hello, World!'});
    client.disconnect();
  }

catch (err) {
    console.error(err);
  }
}

main();

In the example above, we show the entire program; but future examples will isolate one or more specific portions of the code.

Examining the Code

Let us now revisit the code we listed above:

/**
 * The URI to use to connect to AMPS. The URI consists of
 * the transport, the address, and the protocol to use for
 * the AMPS connection. In this case, the transport is `wss`
 * (WebSocket Secure), the address is `127.0.0.1:9007`, and
 * the protocol is `amps`. This connection will be used for
 * JSON messages. Check with the person who manages the AMPS
 * instance to get the connection string to use for your programs.
 */
const uri = 'wss://127.0.0.1:9007/amps/json';


async function main() {
  /**
   * This line creates a new Client object. Client encapsulates
   * a single connection to an AMPS server. Methods on Client allow
   * for connecting, disconnecting, publishing, and subscribing to
   * an AMPS server. The argument to the Client constructor,
   * `examplePublisher`, is a name chosen by the client to identify
   * itself to the server. Errors relating to this connection will be
   * logged with reference to this name, and AMPS uses this name to
   * help detect duplicate messages. AMPS enforces uniqueness for
   * client names when a transaction log is configured, and it is
   * good practice to always use unique client names.
   */
  const client = new Client('examplePublisher');

  /**
   * Now, we attempt to connect to the AMPS server. Most API methods
   * use the Promise pattern to encapsulate asynchronous operations,
   * such as connecting or subscribing. We utilize the async/await
   * syntax to work with the asynchronous code in a somewhat
   * synchronous manner.
   * For example, once the connection is established, the publish
   * function will be called; if the call to connect() fails because
   * the provided address is not reachable, an error will be thrown
   * and caught in the `catch` clause with an Error object that
   * contains information about the occurred error.
   */
  try {
    /**
    * Here, we provide a URI string to the client and establish
    * connection to AMPS.
    */
    await client.connect(uri);

    /**
    * Here, we publish a single message to AMPS on the messages
    * topic, containing the data `Hello, world!`. This data is
    * placed into a JSON message and sent to the server. Upon
    * successful completion of this function, the AMPS client has
    * sent the message to be sent to the server, and subscribers
    * to the messages topic will receive this JSON message:
    * '{"hi": "Hello, world!"}'.
    */
    client.publish('messages', {hi: 'Hello, World!'});

    /**
    * We close the connection to AMPS. It's good practice to
    * close connections when you are done using them as the
    * client object will stay connected otherwise.
    */
    client.disconnect();
  }
  catch (err) {
    // Failed connection error
    console.error(err);
  }
}


// running the above function
main();

Syntax Convention

In the above example and throughout this guide we use the modern JavaScript syntax which is widely supported and typically is used in projects with a build/deployment system, such as webpack, angular-cli, and create-react-app. However, the JavaScript client library fully supports the obsolete syntax used in older browsers and projects without a build system as well. Below is the same program, written in the classic ES5 syntax.

var uri = 'wss://127.0.0.1:9007/amps/json';
var client = new amps.Client('examplePublisher');

client.connect(uri)
    .then(function() {
        client.publish('messages', {hi: 'Hello, world!'});

        client.disconnect();
    })
    .catch(function(error) {
        console.error(error);
    });

Last updated