RTM

RTM

new RTM(endpoint, appkey, opts)

An RTM client is the main entry point for accessing RTM.

To connect a client to RTM, you must call RTM.start(). The RTM SDK attempts to reconnect to RTM if the connection to RTM fails for any reason.

A client instance can be in one of the following connection states:

  • stopped: You called RTM.stop() or RTM disconnected and hasn't yet reconnected.
  • connecting: You called RTM.start() or the client is trying to reconnect to RTM.
  • connected: The client is connected to RTM.
  • awaiting: The client disconnected and is waiting the specified time period before reconnecting. See the minReconnectInterval and maxReconnectInterval options.

For each state, an event occurs when the client enters or leaves the state. Call RTM.on(name, fn) method to add code that's executed when the client transitions into or out of a state. The syntax for the value of name is

[ enter- | leave- ][ stopped | connecting | connected | awaiting ]

For example, RTM.on("enter-connected", myFunction). The next example also shows you how to call RTM.on()

Properties:
Name Type Description
writable boolean

A general indicator of the status of the write buffer. true indicates that the write buffer is shrinking, while false indicates that the write buffer is growing. Test writable to see whether you should continue to write or pause writing.

Source:
Parameters:
Name Type Description
endpoint string

WebSocket endpoint for RTM Available from the Dev Portal.

appkey string

appkey used to access RTM Available from the Dev Portal.

opts object

additional RTM client parameters

Name Type Attributes Default Description
minReconnectInterval int <optional>
1000

minimum time period, in milliseconds, to wait between reconnection attempts

maxReconnectInterval int <optional>
120000

maximum time period, in milliseconds, to wait between reconnection attempts

protocol 'json' | 'cbor' <optional>
'json'

WebSocket subprotocol to use
The SDK automatically converts messages to the subprotocol you choose. For example, if you specify opts.protocol = 'cbor' and then publish a JSON object, the SDK converts it to CBOR.
If you don't specify a subprotocol, RTM defaults to JSON subprotocol.

heartbeatEnabled boolean <optional>
true

enables periodic heartbeat monitoring for the WebSocket connection

authProvider object <optional>

object that manages authentication for the client. See auth.js

heartbeatInterval int <optional>
60000

interval, in milliseconds, to wait between heartbeat messages

highWaterMark int <optional>
4194304

4MB. High water mark in bytes. If the number of bytes in the WebSocket write buffer exceeds this value, writeable is set to false.

lowWaterMark int <optional>
2097152

2MB. Low water mark, in bytes. If the WebSocket write buffer rises above highWaterMark and then drops below lowWaterMark, writeable is set to true.

checkWritabilityInterval int <optional>
100

Interval, in milliseconds, between checks of the queue length and updates of the writeable property if necessary.

proxyAgent object <optional>

proxy server agent. A custom http.Agent implementation like: https-proxy-agent https://github.com/TooTallNate/node-https-proxy-agent#ws-websocket-connection-example socks-proxy-agent https://github.com/TooTallNate/node-socks-proxy-agent#ws-websocket-connection-example

Throws:

TypeError is thrown if mandatory parameters are missing or invalid.

Type
TypeError
Example
// Creates an RTM client
var rtm = new RTM('YOUR_ENDPOINT', 'YOUR_APPKEY');

// Creates a new subscription to the channel named 'your-channel'
var subscription = rtm.subscribe('your-channel', RTM.SubscriptionMode.SIMPLE);

// Adds a subscription event listener that logs messages to the console as they arrive.
// The subscription receives all messages in the subscribed channel
subscription.on('rtm/subscription/data', function (pdu) {
    pdu.body.messages.forEach(console.log);
});

// Sets a connection event listener that publishes a message to the channel named
// <code>your-channel</code>
// when the client is connected to RTM (the client enters the 'connected' state)
rtm.on('enter-connected', function () {
  rtm.publish('your-channel', {key: 'value'});
});

// Sets a client event listener that checks incoming messages to see if they indicate an error.
// <code>rtm.on()</code> is called for all incoming messages.
rtm.on('data', function (pdu) {
  if (pdu.action.endsWith('/error')) {
    rtm.restart();
  }
});

// Starts the client
rtm.start();

Extends

Namespaces

SubscriptionMode

Methods

(static) roleSecretAuthProvider(role, roleSecret, opts) → {function}

Creates a role-based authentication provider for the client

The role-based authentication method is a two-step authentication process based on the HMAC process, using the MD5 hashing routine:

  • The client obtains a nonce from the server in a handshake request.
  • The client then sends an authorization request with its role secret key hashed with the received nonce.

To get a role secret key for your application, go to the Dev Portal.

Source:
Parameters:
Name Type Description
role string

role name set in the Dev Portal

roleSecret string

role secret key

opts object

additional authentication options

Name Type Attributes Default Description
timeout int <optional>
30000

amount of time, in milliseconds, before the authentication operation times out

Throws:

thrown if mandatory parameters are missing or invalid

Type
TypeError
Returns:
Type:
function

authentication provider for the role-based authentication method

delete(channel, onAckopt) → {void}

Deletes the value for the associated channel. The RTM client must be connected.

Source:
Parameters:
Name Type Attributes Description
channel string

Channel name.

onAck function <optional>

Callback function that's invoked when RTM responds to the publish request. RTM passes the response PDU to this function. If you don't specify onAck, RTM doesn't send a response PDU.

Throws:

thrown if required parameters are missing or invalid

Type
TypeError
Returns:
Type:
void
Example
rtm.delete('channel', function (pdu) {
    console.log(pdu);
})

fire(name, …args) → {void}

Executes all handlers attached for the specified event type.

The event specified in name is an RTM or Subscription event that has an attached event handler function (see the on() function).

Inherited From:
Source:
Parameters:
Name Type Attributes Description
name string

name of an event that has attached handlers

args Object <repeatable>

event arguments.

Returns:
Type:
void

getSubscription(subscriptionId) → {Subscription}

Returns the existing Subscription object for the specified subscription id.

Source:
Parameters:
Name Type Description
subscriptionId string

the id for an existing Subscription object

Throws:

thrown if subscriptionId is missing, invalid, or if a Subscription object with that id doesn't exist.

Type
TypeError
Returns:
Type:
Subscription

the Subscription object

isConnected() → {boolean}

Returns true if the client is in the connected state.

In this state, the WebSocket connection to RTM is established and any requested authentication has completed successfully .

Source:
Returns:
Type:
boolean

true if the client is in the connected state, otherwise false

isStopped() → {boolean}

Returns true if the RTM client is in the stopped state.

Source:
Returns:
Type:
boolean

true if the client is in the stopped state, otherwise false

off(name, fn) → {void}

Removes an event handler.

The event specified in name is an RTM or Subscription event that has an attached event handler function (see the on() function).

The Protocol Data Unit (PDU) for the event is passed to the fn function parameter.

Inherited From:
Source:
Parameters:
Name Type Description
name string

event name

fn function

event handler function

Returns:
Type:
void

on(name, fn) → {void}

Attaches an event handler function for the event specified in name.

The event is usually related to a client or subscription state. It may also be an event that occurs when the client or subscription receives information from RTM. For example, the the following are RTM client events:

  • data: The client received a PDU from RTM.
  • enter-connected: The client is now connected to RTM.
A possible event for a Subscription is enter-subscribed.

The fn parameter is a function that's invoked when the event occurs. The PDU for the event is passed to this function.

Inherited From:
Source:
Parameters:
Name Type Description
name string

event name

fn function

event handler function

Returns:
Type:
void

publish(channel, message, onAckopt) → {void}

Publishes a message to a channel. The client must be connected.

Source:
Parameters:
Name Type Attributes Description
channel string

channel name

message JSON | Uint8Array


JSON object or binary data containing the message to publish
The type you choose is independent of the subprotocol you're using for your client. The SDK automatically converts the message to the correct format before sending it to RTM.

onAck function <optional>

Callback function that's invoked when RTM responds to the publish request. RTM passes the response PDU to this function. If you don't specify onAck, RTM doesn't send a response PDU.

Throws:

thrown if required parameters are missing or invalid

Type
TypeError
Returns:
Type:
void
Example
// Publishes to the channel named "channel", and provides a callback function that's invoked when
// RTM responds to the request. If the PDU "action" value doesn't end with "ok", the function
// logs an error.
rtm.publish('channel', {key: 'value'}, function (pdu) {
  if (!pdu.action.endsWith('/ok')) {
    console.log('something went wrong');
  }
});

read(channel, onAckOrOptsopt) → {void}

Reads the latest message written to a specific channel, as a Protocol Data Unit (PDU). The client must be connected.

The callback function you specify receives a PDU in the same format as the subprotocol you specify in the client constructor RTM. RTM automatically converts messages.

Source:
Parameters:
Name Type Attributes Description
channel string

name of the channel to read from

onAckOrOpts function <optional>

Callback function that's invoked when RTM responds to the read request. RTM passes the response PDU to this function. If you don't specify onAck, RTM doesn't send a response PDU.

Throws:

thrown if required parameters are missing or invalid

Type
TypeError
Returns:
Type:
void
Example
// Reads from the channel named 'channel' and prints the response PDU
rtm.read('channel', function (pdu) {
    console.log(pdu);
})

read(channel, optsopt) → {void}

Reads the latest message written to specific channel, as a Protocol Data Unit (PDU). The client must be connected.

Source:
Parameters:
Name Type Attributes Default Description
channel string

name of the channel to read from

opts object <optional>
{}

Additional options in the read PDU that's sent to RTM in the request. For more information, see the section "Read PDU" in the "RTM API" chapter of Satori Docs/em>.

Name Type Attributes Default Description
bodyOpts object <optional>
{}

Additional options in the body element of the read PDU that's sent to RTM in the request.

onAck function <optional>

Callback function that's invoked when RTM responds to the read request. RTM passes the response PDU to this function. If you don't specify onAck, RTM doesn't send a response PDU.

Throws:

thrown if required parameters are missing or invalid

Type
TypeError
Returns:
Type:
void
Example
// Reads from the channel named 'channel', starting at the position specified by the
// "position" key.
// Prints the response PDU.
rtm.read('channel', {
  bodyOpts: { position: '1485444476:0' },
  onAck: function (pdu) {
    console.log(pdu);
  }
})

restart() → {void}

Calls RTM.stop() followed by RTM.start().

Source:
Returns:
Type:
void

resubscribe(channelOrSubId, mode, bodyOpts, onCompletedopt) → {void}

Updates an existing Subscription object. Existing Subscription event handlers are copied to the updated object.

Use this method to change an existing subscription. For example, use it to add or change a streamview.

Source:
Parameters:
Name Type Attributes Description
channelOrSubId string

subscription id or channel name for the existing subscription

mode RTM.SubscriptionMode

Contains flags that determine the resubscribe behavior of the RTM SDK and RTM. See SubscriptionMode.

bodyOpts Object

Properties for the updated Subscription object. See RTM.subscribe(channelOrSubId, opts) for the supported property names.

onCompleted function <optional>

function to execute on the updated Subscription object

Throws:

thrown if mandatory parameters are missing or invalid.

Type
TypeError
Returns:
Type:
void

start() → {void}

Starts the client.

The client begins to establish the WebSocket connection to RTM and then tracks the state of the connection. If the WebSocket connection drops for any reason, the JavaScript SDK attempts to reconnect.

Use [RTM.on(name, fn)]RTM.on() to define application functionality, for example, when the application enters or leaves the connecting or connected states.

Source:
Returns:
Type:
void

stop() → {void}

Stops the client. The RTM SDK starts to close the WebSocket connection and does not start it again unless you call RTM.start().

Use this method to explicitly stop all interaction with RTM.

Use RTM.on("enter-stopped", function()) or RTM.on("leave-stopped", function()) to provide code that executes when the client enters or leaves the stopped state.

Source:
Returns:
Type:
void

subscribe(channelOrSubId, mode, bodyOptsopt) → {Subscription}

Creates a subscription to the specified channel.

When you create a subscription, you can specify additional options in the bodyOpts parameter. For example, you can specify a streamview or specify what the SDK does when it resubscribes after a reconnection.

The callback function you specify for the subscription always receives PDUs in the form of JavaScript objects.

Source:
See:
Parameters:
Name Type Attributes Default Description
channelOrSubId string

Contains a channel name or a subscription id. If you don't specify the filter field in bodyOpts, specify the channel name. Otherwise, specify the channel name in the stream SQL in the filter field, and specify a subscription id in channelOrSubId.

mode RTM.SubscriptionMode

Contains flags that determine the resubscribe behavior of the RTM SDK and RTM. See SubscriptionMode.

bodyOpts object <optional>
{}

Contains additional options for the subscription

Name Type Attributes Default Description
force boolean <optional>
false

Determines how RTM should act if the subscribe request contains a subscription_id that already exists. If true, RTM re-subscribes or creates a new subscription, depending on the specified subscription parameters. If false, RTM returns an error.

fast_forward boolean <optional>
false

Determines how RTM should act if it detects that the next message position for the subscription is pointing to an expired message (out of sync condition). If true, RTM moves the next message position to the least recent un-expired message in the channel. If false, RTM returns an error and terminates the subscription.

position int <optional>

Position of a message in the channel. If you don't specify the history field, RTM uses this position as the next message position for the subscription. Otherwise, RTM interprets the value in history as an offset from the value of position.

history object <optional>

Object that contains history parameters.

Name Type Attributes Description
count int <optional>

Offset from a message position, specified as a number of messages. RTM starts the subscription this many messages before the position that the subscription otherwise starts with. If you specify bodyOpts.position, RTM uses that position as the starting point for the offset. Note: If you specify count, you can't specify age.

age int <optional>

Offset from a message position, specified as a duration in seconds. RTM starts the subscription at the least recent message that's this many seconds older than the position that the subscription otherwise starts with. If you specify bodyOpts.position, RTM uses that position as the starting point for the offset. Note: If you specify age, you can't specify count.

filter string <optional>

Contains a stream SQL statement that selects, transforms, or aggregates messages in the specified channel

period int <optional>

Specifies a duration in seconds for each partition in an aggregate view. The maximum value is 60 (1 minute).

Throws:

thrown if mandatory parameters are missing or invalid.

Type
TypeError
Returns:
Type:
Subscription
  • subscription object
Examples
// Creates a new RTM client
var rtm = new RTM('YOUR_ENDPOINT', 'YOUR_APPKEY');

// Creates a subscription with the name 'your-channel'
var subscription = rtm.subscribe('your-channel', RTM.SubscriptionMode.SIMPLE);

// Writes incoming messages to the log
subscription.on('rtm/subscription/data', function (pdu) {
    pdu.body.messages.forEach(console.log);
});

// Starts the client
rtm.start();
// Creates a new RTM client
var rtm = new RTM('YOUR_ENDPOINT', 'YOUR_APPKEY');

// Subscribes to the channel named 'my-channel' using a streamview
var subscription = rtm.subscribe('my-filter', RTM.SubscriptionMode.SIMPLE, {
  filter: 'SELECT * FROM my-channel WHERE object.param >= 1 OR object.id == 0',
});

// Writes incoming messages to the log
subscription.on('rtm/subscription/data', function (pdu) {
  pdu.body.messages.forEach(console.log);
});

// Sets a client event listener, for unsolicited subscription PDUs, that reacts to an error PDU
// by restarting the client connection. The PDU is passed as a parameter.
rtm.on('data', function (pdu) {
  if (pdu.action.endsWith('/error')) {
    rtm.restart();
  }

rtm.start();

unsubscribe(subscriptionId, onAckopt) → {void}

Removes the specified subscription.

Source:
Parameters:
Name Type Attributes Description
subscriptionId string

Subscription id or channel name.

onAck function <optional>

Callback function that's invoked when RTM responds to the unsubscribe request. RTM passes the response PDU to this function. If you don't specify onAck, RTM doesn't send a response PDU.

Throws:

thrown if required parameters are missing or invalid

Type
TypeError
Returns:
Type:
void

write(channel, value, onAckopt) → {void}

Writes a value to the specified channel. The client must be connected.

Source:
Parameters:
Name Type Attributes Description
channel string

name of the channel to write to

value JSON | Uint8Array


JSON object or binary data containing the message to write
The type you choose is independent of the subprotocol you're using for your client. The SDK automatically converts the message to the correct format before sending it to RTM.

onAck function <optional>

Callback function that's invoked when RTM responds to the publish request. RTM passes the response PDU to this function. If you don't specify onAck, RTM doesn't send a response PDU.

Throws:

thrown if required parameters are missing or invalid

Type
TypeError
Returns:
Type:
void
Example
// Writes the string 'value' to the channel named 'channel' and prints the response PDU.
rtm.write('channel', 'value', function (pdu) {
    console.log(pdu);
})