Getting Started

  1. Install the SDK:

    • The easy way:

      <script src="https://unpkg.com/@realmq/web-sdk/dist/realmq.min.js"></script>
    • The flexible way:

      $ yarn add @realmq/web-sdk
      # or
      $ npm install @realmq/web-sdk
  2. Initialize the SDK:

    const realmq = new RealMQ('<AUTH_TOKEN>');
    
  3. Start implementing:

    // eg. load some data
    const channels = await realmq.channels.list();
    
    // or connect to the real-time API
    await realmq.rtm.connect();
    realmq.autoSubscribe();
    
    // listen for messages in some-channel
    realmq.rtm.on('some-channel/message', function channelMessageHandler(message) {
      console.warn('received new message in channel ', ${message.channel}, ':', message.data);
    });
    

Concepts

  • Our SDK utilizes promises where possible.
  • We provide convenient interfaces to work with resources retrieve, list, create, update and remove methods.
  • realmq.rtm.* provides real-time functionality
  • Each API resource has its own namespace.
  • There are two access groups (scopes). Every method has a description of what scopes are allowed to perform that action.
    • Admin Full management capabilities, use for implementing your real-time business logic
    • User Restricted access, use for logic on behalf of a single user/device/bot

Initialization

Add the SDK to your html app:

<script src="https://unpkg.com/@realmq/web-sdk"></script>

Now you can initialize your real-time client.

const authToken = '<AUTH_TOKEN>';
const options = {
  host: 'realmq.your-domain.com'
};
const realmq = new RealMQ(authToken, options);
Parameters
String authToken
A secret RealMQ auth token.
Object options
(optional)
String options.host
(optional)
Set this if you run against a dedicated or on-premise deployment.
Default: realmq.com
Boolean options.autoConnect
(optional)
Automatically connect the client to the RealMQ broker upon initialization by implicitly calling realmq.rtm.connect().
Default: false
Boolean options.enableSubscriptionSyncEvents
(optional)
Emit subscription synchronization events subscription-created, subscription-updated & subscription-deleted events
Default: true
Boolean options.autoSubscribe
(optional)
Automatically subscribes the client to all channels that the connecting user has access to by calling realmq.autoSubscribe() after connecting to the RealMQ broker. If enableSubscriptionSyncEvents is enabled the client automatically updates the subscriptions during runtime.
👉 Note: This implies autoConnect = true.
Default: false

Channels

Create a channel

Admin

// create a simple channel
const channel1 = await realmq.channels.create();

// create a channel with a custom id
const channel2 = await realmq.channels.create({ id: 'awesome-channel' });

// create a channel with a message storage limit of 7 days
const channel3 = await realmq.channels.create({
  id: 'messages-within-the-last-week',
  features: {
    persistence: {
      enabled: true,
      duration: '7d',
    },
  },
});
Parameters
String id
(optional)
see Custom Ids
Object properties
(optional)
see Custom Properties
Object features
(optional)
Additional channel features
Object features.persistence
(optional)
Message persistence settings for this channel
Boolean features.persistence.enabled
If set to true, the messages published in this channel are persisted for later access.
String features.persistence.duration
(optional)
Time interval to persist messages published on the channel. If not set messages will be persisted forever. Supported units are s, m, h, and d

Retrieve a channel

Admin User

const channel = await realmq.channels.retrieve('channel-id');
Parameters
String channelId

List all accessible channels

Admin User

Fetch a PaginatedList of Channels.

const channelList1 = await realmq.channels.list();
const channelList2 = await realmq.channels.list({ limit: 5, offset: 5 });
Parameters
Int offset
(optional)
see Pagination Params
Int limit
(optional)
see Pagination Params

Update a channel

Admin

const channel = await realmq.channels.update('channel-id', [
  {
    op: 'replace',
    path: '/properties/memberCount',
    value: 47
  }
]);
Parameters
String channelId
Array patch
Update channel properties via JSON-patch (RFC6902).

Remove a channel

Admin

const channel = await realmq.channels.remove('channel-id');
Parameters
String channelId

Retrieving channel messages

Admin User

Fetch a PaginatedList of persisted messages within a Channel.

👉 Note: You have to enable channel persistence to retrieve messages from this resource.

const messages = await realmq.messages.list({
  channel: 'channel-id',
  offset: 10,
  limit: 10,
  from: '2023-08-01T11:03:42.58Z',
  to: '2023-08-01T11:03:42.58Z',
});
Parameters
String channel
Number offset
(optional)
see Pagination Params
Number limit
(optional)
see Pagination Params
Date from
(optional)
Only show messages with a timestamp equal or later than this date
Date to
(optional)
Only show messages with a timestamp smaller than or equal this date

Subscriptions

Create a subscription

Admin

const subscription = await realmq.subscriptions.create({
  channelId: 'test-channel',
  userId: 'test-user',
  allowRead: true
});
Parameters
String id
(optional)
An optional Custom Id
String channelId
(optional)
An optional Channel reference.
👉 Note: If no channel is specified or the specified channel doesn’t exist it will be auto-created.
String userId
(optional)
An optional User reference.
👉 Note: If no user is specified or the specified user doesn’t exist it will be auto-created.
Boolean allowRead
(optional)
Whether the user will be able to receive channel messages.
Boolean allowWrite
(optional)
Whether the user will be able to publish messages to the channel.

Retrieve a subscription

Admin User

const subscription = await realmq.subscriptions.retrieve('subscription-id');
Parameters
String subscriptionId

List all subscriptions

User

Fetch a PaginatedList of Subscriptions.

const subscriptionList1 = await realmq.subscriptions.list();
const subscriptionList2 = await realmq.subscriptions.list({ limit: 5, offset: 5 });
Parameters
Int offset
(optional)
see Pagination Params
Int limit
(optional)
see Pagination Params

Update a subscription

Admin

const user = await realmq.subscriptions.update('subscription-id', [
  {
    op: 'replace',
    path: '/allowRead',
    value: true
  }
]);
Parameters
String subscriptionId
Array patch
Update user properties via JSON-patch (RFC6902).

Remove a subscription

Admin

const subscription = await realmq.subscriptions.remove('subscription-id');
Parameters
String subscriptionId

Tokens

Create a token

Admin

Create a new auth token and passively create a new user if not existing yet. If you want to create an auth token for an existing user you have to pass its id as userId.

const user1 = await realmq.tokens.create();
const user2 = await realmq.users.create({ id: 'my-token-id', userId: 'test-user', scope: 'user' });
Parameters
String id
(optional)
An optional Custom Ids
String userId
(optional)
An optional User reference.
👉 Note: If no user is specified or the specified user doesn’t exist it will be auto-created.
String scope
(optional)
Scope of the token. Possible values are admin and user.
Default: user
String description
(optional)
An optional auth token description.

Retrieve a token

Admin User

Find an auth token by its id.

const user = await realmq.tokens.retrieve('token-id');
Parameters
String tokenId

List all tokens

Admin User

Fetch a PaginatedList of Tokens of the current user, or system-wide if the request is performed as admin.

const userList1 = await realmq.tokens.list();
const userList2 = await realmq.tokens.list({ limit: 5, offset: 5 });
Parameters
Int offset
(optional)
see Pagination Params
Int limit
(optional)
see Pagination Params

Update a token

Admin User

Update auth token via JSON-patch (RFC6902).

Patchable Fields
description
const user = await realmq.tokens.update('token-id', [
  {
    op: 'replace',
    path: '/description',
    value: 'Session on Chrome Linux'
  }
]);
Parameters
String tokenId
Array patch
Update token description via JSON-patch (RFC6902).

Remove a token

Admin User

Delete the auth token and invalidate the session.

const user = await realmq.tokens.remove('token-id');
Parameters
String tokenId

Users

Create a user

Admin

const user1 = await realmq.users.create();
const user2 = await realmq.users.create({ id: 'awesome-user' });
Parameters
String id
(optional)
An optional Custom Ids
Object properties
(optional)
A map of Custom Properties

Retrieve a user

Admin

const user = await realmq.users.retrieve('user-id');
Parameters
String userId

List all users

User

Fetch a PaginatedList of Users.

const userList1 = await realmq.users.list();
const userList2 = await realmq.users.list({ limit: 5, offset: 5 });
Parameters
Int offset
(optional)
see Pagination Params
Int limit
(optional)
see Pagination Params

Update a user

Admin

const user = await realmq.user.update('user-id', [
  {
    op: 'replace',
    path: '/properties/avatar',
    value: 'https://api.adorable.io/avatars/64/avatar.png'
  }
]);
Parameters
String userId
Array patch
Update user properties via JSON-patch (RFC6902).

Remove a user

Admin

var user = await realmq.users.remove('user-id');
Parameters
String userId

Real-time Gateway

Access our real-time API through realmq.rmt.*. Before you can send or receive messages, you need to establish a connection.

await realmq.rtm.connect();

👉 Info: There is also a realmq.rtm.disconnect() method.

Events

realmq.rtm emits the following events:

  • connected
  • reconnected
  • disconnected
  • message
  • {channel}/message
  • message-sent

Let’s register an event handler with realmq.rtm.on:

function onConnect() {}

realmq.rtm.on('connected', onConnect);

You can remove event handlers with realmq.rtm.off:

realmq.rtm.off('connected', onConnect);

Subscribe to a channel

After subscribing to a channel you will receive all messages published to that channel.

await realmq.rtm.subscribe({
  channel: 'test-channel'
});

👉 Note: Subscribe will fail if you do not have a read-enabled subscription on that channel.

Unsubscribe from a channel

After unsubscribing from a channel you will not receive any messages through that channel.

await realmq.rtm.unsubscribe({
  channel: 'test-channel'
});

Receive messages

Whenever a message hits the client, the SDK will emit message events.

  • message will be emitted for every message.
  • {channel}/message will be emitted for every message in a particular channel
realmq.rtm.on('message', function messageHandler(message) {});
realmq.rtm.on('some-channel/message', function channelMessageHandler(message) {});

The message object provides the following properties:

Message Properties
String channel
The channel in which the messag was published.
Uint8Array raw
The raw message buffer.
Mixed data
Contains the json decoded buffer data.
Error error
Only set if data was accessed and json decoding failed.

👉 Note: If your messages contain binary, you should access raw instead of data. Otherwise a JSON Parse exception might be raised.

Publish a message

We do not restrict you on what data of which format you publish.

You can send plain string messages:

await realmq.rtm.publish({ channel: 'test-channel', message: 'Welcome!' });

Or if you prefer binary:

const message = new Uint8Array([0x57, 0x65, 0x6c, 0x63, 0x6f, 0x6d, 0x65, 0x21]);
await realmq.rtm.publish({ channel: 'test-channel', message });

Or anything else:

const message = { '❤️': 'Welcome!' };
await realmq.rtm.publish({ channel: 'test-channel', message });

👉 Note: Non binary messages will be automatically JSON encoded.
👉 Note: Publish will fail if you do not have a write-enabled subscription on that channel.