Rooms

A room is a virtual environment where users can interact by sending and receiving events. Rooms allow for various types of functionality, such as managing presence, subscribing to specific events, and publishing messages.

In a room, you can handle presence updates, subscribe or unsubscribe to events, and manage event history, among other actions. This powerful mechanism enables you to organize real-time interactions and event handling within a structured context, where each room serves as a dedicated space for its participants.


join()

Asynchronous function to join or create a "room" in which to send or recieve events.

await relayBox.join();

Returns Room object for optional chaining

class Room {
  constructor(roomId: string, socketManager: SocketManager, presencefactory: PresenceFactory, metricsFactory: MetricsFactory);
  readonly roomId: string;
  connect(): void;
  disconnect(): void;
  presence: Presence | null;
  metrics: Metrics | null;
  subscribe(eventOrHandler: string | SocketEventHandler, eventHandler?: SocketEventHandler): Promise<this>;
  unsubscribe(eventOrHandler?: string | SocketEventHandler, eventHandler?: SocketEventHandler): Promise<this>;
  publish<T>(event: string, userData: T): Promise<any>;
  leave(): Promise<void>;
}
ArgumentDescriptionType
1

Room Name: Specify the name of the room you want to join or create. If the room already exists, you will join it; if not, it will be created.

string

Example:

const room = relayBox.join('myRoomName');

room.subscribe()

Asynchronous function to subscribe to all or individual events that are broadcast to a room.

  • Requires subscribe permission
await room.subscribe();

Returns Room object for optional chaining

ArgumentDescriptionType
1

Event Name or Handler (optional): The first argument can be the name of the event you wish to subscribe to or an event handler function.

string / function
2

Event Handler (optional): The second argument can be an event handler function. If provided, it will be subscribed to the event.

function

Example:

// Subscribe to all room events
await room.subscribe((data: any) => {});

// Subscribe to events matching 'myEventName'
await room.subscribe('myEventName', (data: any) => {});

room.unsubscribe()

Asynchronous function to unsubscribe from all or individual event(s)

await room.subscribe();

Returns Room object

ArgumentDescriptionType

1
(optional)

Event Name or Handler (optional): The first argument can be the name of the event you wish to unsubscribe from or an event handler function. If you provide a specific event handler function, only that handler will be removed from the event.

string / function

2
(optional)

Event Handler (optional): The second argument can be an event handler function. If provided, it will be removed from the specified event.

function

Example:

// Unsubscribe from a specific event by name
await room.unsubscribe('message');

// Unsubscribe a specific event handler from an event
const handler = (data) => console.log(data);
await room.unsubscribe('message', handler);

// Unsubscribe from all events
await room.unsubscribe();

room.publish()

Asynchronous function to publish an event to a subscribers at room level.

  • Requires publsh permission
await room.publish();

Returns Room object for optional chaining

ArgumentDescriptionType
1

Event Name (required): The name of the event you wish to publish to subscribers of this event.

string
2

User data (required): The second argument must be the data you wish to attach to the event for processing by subscribers.

function

Example:

const data = {
  hello: 'room'
};

// publish 'myEventName' containing data to subscribers in room
await room.publish('myEventName', data);

room.presence.join()

Asynchronous function to join a presence set.

  • Requires "presence" permission
  • Requires connection clientId
await room.presence.join();

Returns void

ArgumentDescriptionType

1
(optional)

User Data (optional): Additional arbitrary data to be transmitted with join eventstring / object / array / blob / buffer

Example:

const userData = {
  name: 'foo'
};

// Send additional user data to "join" event subscribers
await room.presence.join(userData)

room.presence.leave()

Asynchronous function to leave a presence set.

  • Requires "presence" permission
  • Requires connection clientId
await room.presence.leave();

Returns void

ArgumentDescriptionType

1
(optional)

User Data (optional): Additional arbitrary data to be transmitted with leave event

string / object / array / blob / buffer

Example:

const userData = {
  name: 'foo'
};

// Send additional user data to "leave" event subscribers
await room.presence.leave(userData)

room.presence.update()

Asynchronous function to update arbitrary user data associated with a presence set connection.

  • Requires "presence" permission
  • Requires connection clientId
await room.presence.update();

Returns void

ArgumentDescriptionType

1
(optional)

User Data (optional): Updated arbitrary user data tp be published to presence update subscribers

string / object / array / blob / buffer

Example:

const userData = {
  latitude: 0.15652,
  longitude: 0.1435
};

// Send additional user data to "update" event subscribers
await room.presence.update(userData)

room.presence.subscribe()

Asynchronous function to subscribe to presence events for a room.

  • Requires "presence" permission
await room.presence.subscribe();

Returns void

ArgumentDescriptionType
1

Event Name or Handler (optional): The first argument can be the name of the presence event you wish to subscribe to or an event handler function.

string (join | leave | update) / function
2Event Handler (optional): The second argument can be an event handler functionfunction

Example:

// Subscribe to all room events
await room.presence.subscribe((data: any) => {});

// Subscribe to events matching 'join'
await room.presence.subscribe('join' | 'leave' | 'update', (data: any) => {});

room.presence.unsubscribe()

Asynchronous function to unsubscribe from all or individual presence event(s)

await room.presence.unsubscribe();

Returns void

ArgumentDescriptionType

1
(optional)

Event Name or Handler (optional): The first argument can be the name of the presence event you wish to unsubscribe from or an event handler function. If you provide a specific event handler function, only that handler will be removed from the event.

string (join | leave | update) / function

2
(optional)

Event Handler (optional): The second argument can be an event handler function. If provided, it will be removed from the specified event.

function

Example:

// Unsubscribe from a specific presence event by name
await room.presence.unsubscribe('join');

// Unsubscribe a specific presence event handler from an event
const handler = (data) => console.log(data);
await room.presence.unsubscribe('join', handler);

// Unsubscribe from all events
await room.presence.unsubscribe();

room.presence.get()

Asynchronous function to fetch all presence connections for a given room.

  • Requires "presence" permission
await room.presence.get<T>();

Returns array of PresenceEvent

interface PresenceEvent<T = any> {
  id: string;
  timestamp: string;
  data: T;
}

Example:

// fetch active presence connections for a room
const presenceUsers = await room.presence.get();

// Recomended usage...
await room.presence.subscribe((data: any) => {
  const presenceUsers = await room.presence.get();
});

room.presence.getCount()

Asynchronous function to fetch count of presence connections for a given room.

  • Requires "presence" permission
await room.presence.getCount();

Returns number

Example:

// fetch active presence connections for a room
const presenceCount = await room.presence.getCount();

// Recomended usage...
await room.presence.subscribe((data: any) => {
  const presenceCount = await room.presence.getCount();
});

room.metrics.subscribe()

Asynchronous function to subscribe to metrics events for a room.

  • Requires "metrics" permission
await room.metrics.subscribe();

Returns void

ArgumentDescriptionType
1Event Handler (optional): An event handler functionfunction

Example:

// Subscribe to all metrics events
await room.metrics.subscribe((data: any) => {});

room.metrics.unsubscribe()

Asynchronous function to unsubscribe from all metrics events

await room.metrics.unsubscribe();

Returns void

ArgumentDescriptionType

1
(optional)

Event Handler (optional): An event handler function. If you provide a specific event handler function, only that handler will be removed from the event.

function

Example:

// Unsubscribe a specific metrics event handler
const handler = (data) => console.log(data);
await room.metrics.unsubscribe(handler);

// Unsubscribe from all metrics events
await room.metrics.unsubscribe();

room.history.get()

  • Requires "history" permission

Asynchronous function to retrieve past messages for a given room.

await room.history.get();

The get() method takes a single argument, a history options object.

ArgumentDescriptionType

1
(optional)

History options: The first argument can be an object containing the room history query paramters. When no options are provided, the last 100 messages will be retrieved along with an iterator function to retrieve the next batch of messages.

object

Returns an object providing,

  • items - The list of message items
  • next - A function to retrieve the next batch of messages
{
  items: any[];
  next: () => Promise<HistoryResponse>;
}

Example:

The example below will retrieve the message history for a room in batches of 100 messages beginning with the most recent message.

const room = await relaybox.join('myRoom');

const history = await room.history.get({
  start: number,
  end: number,
  order: 'asc' | 'desc', // default: 'desc'
  limit: number // default: 100
});

To apply a filter to the retrieved messages, you can pass a filter object to to the get() method. The following options are available:

KeyDescriptionType
start

Milliseconds since the Unix epoch. The oldest message to receive. Only messages at or after this time will be returned.

number
end

Milliseconds since the Unix epoch. The latest message to receive. Only messages at or before this time will be returned.

number
order

Specify the order of the messages. The default order is desc, which means the most recent messages will be returned first. Set the order to asc to return the oldest messages first.

string


'asc' | 'desc'

limit

Number of items to include in each batch. The default limit is 100. This parameter is useful for lazy loading message history.

number
1 - 100


room.history.next()

  • Requires "history" permission

Asynchronous iterator function to retrieve the next batch of message history for a given room.

// const history = await room.history.get();
await history.next();

Returns list of items along with a batch iterator function (if applicable).

{
  items: any[];
  next: () => Promise<HistoryResponse>;
}

Example:

The example below will retrieve the message history for a room in batches of 100 messages beginning with the most recent message.

const room = await relaybox.join('myRoom');

let history = await room.history.get();

while (history.next) {
  history = await history.next();
  console.log(history.items);
}

room.intellect.query()

  • Requires "intellect" permission

RelayBox intellect search index provides a powerful search capability for rooms. The query() method allows you to query past messages and content uploaded to a room's cloud storage service using natural language and receive a conversational response.

const result = await room.intellect.query('Please remind me when Emma is getting back from holiday?');

Returns a response and a conversationId. The conversationId can be used to provide context to further interactions to allow for a conversational search experience.

{
  "response": "Emma mentioned she'll be getting back from holiday on the 15th.",
  "conversationId": "6a8e6d46-4c8e-4664-b5d8-7f9082de6d31"
}

Example:

In the example below, a room called "myRoom" was joined. The query() method is then called with a natural language query. The response is returned along with a conversationId that can be used to provide context to further interactions.

const room = await relaybox.join('myRoom');

const result = room.intellect.query('Please remind me when Emma is getting back from holiday?');

The following options are available:

KeyDescriptionType
conversationId

To continue a conversation with the intellect search service, pass the conversationId. Previous messages form the context of the next question to get more relevant answers based on previous interactions.

uuid
assetId

Every cloud storage item has a unique assetId. By passing this reference to the intellect search service, you can query specific assets that have been uploaded to a room's cloud storage service.

uuid

room.storage.put()

  • Requires "storage" permission

RelayBox storage provides a way to upload files to a room. By using the put() method, you are able to upload files to a room's cloud storage service.

const response = await room.storage?.put(files);

Returns CloudStorageAsset metadata object.

[
  {
    "id": "00000000-0000-0000-0000-000000000000",
    "appPid": "public-app-id",
    "keyId": "api-key-id",
    "roomId": "myRoom",
    "clientId": "client-id",
    "name": "test.pdf",
    "type": "application/pdf",
    "size": 0,
    "encoding": "7bit",
    "createdAt": "2024-11-23T14:52:19.365Z",
    "updatedAt": "2024-11-23T14:52:19.365Z"
  }
]

Example:

The example below uses a react functional component method and a zod schema that has been attached to the onsubmit action of a form. the method passes a file list directly to the put() method.

const formSchema = z.object({
  files: z
    .instanceof(FileList)
    .optional()
    .refine((fileList) => !fileList || fileList.length > 0, {
      message: 'Please upload at least one file.'
    })
});

async function onSubmit(values: z.infer<typeof formSchema>) {
  if (values.files?.length) {
    try {
      const response = await room.storage?.put(values.files);

      console.log(`File uploaded`, response);
    } catch (error) {
      console.error('Error uploading files:', error);
    }
  }

  form.reset();
}

room.storage.list()

  • Requires "storage" permission

Retrieve a paginated list of files uploaded to a room's cloud storage service.

const response = await room.storage?.list();

Returns paginated list of CloudStorageAsset metadata objects.

{
  "count": 2,
  "items": [
    {
      "id": "00000000-0000-0000-0000-000000000000",
      "appPid": "public-app-id",
      "keyId": "api-key-id",
      "roomId": "myRoom",
      "clientId": "client-id",
      "name": "test.pdf",
      "type": "application/pdf",
      "size": 0,
      "encoding": "7bit",
      "createdAt": "2024-11-23T14:52:19.365Z",
      "updatedAt": "2024-11-23T14:52:19.365Z"
    }
  ]
}

Example:

The example below returns a paginated list of files uploaded to a room's cloud storage service. The results will start from the 11th result and return up to 10 items

const response = await room.storage?.list({
  offset: 10,
  limit: 10
});

The following options are available:

KeyDescriptionType
offset

To allow for pagination. The offset attribute is the number of items to skip from 0. For example, if the value of offset is 2, the first two items will be skipped.

number
limit

To allow for pagination. The limit attribute is the number of items to return. For example, if the value of limit is 2, two items will be returned.

number

room.storage.getMetaData()

  • Requires "storage" permission

Retrieve metadata for a file uploaded to a room's cloud storage service.

const assetMetadata = await room.storage?.getMetadata();

Returns CloudStorageAsset metadata object.

{
  "id": "00000000-0000-0000-0000-000000000000",
  "appPid": "public-app-id",
  "keyId": "api-key-id",
  "roomId": "myRoom",
  "clientId": "client-id",
  "name": "test.pdf",
  "type": "application/pdf",
  "encoding": "7bit",
  "createdAt": "2024-11-23T14:52:19.365Z",
  "updatedAt": "2024-11-23T14:52:19.365Z"
}

Example:

The example below retrives metadata for a file uploaded to a room's cloud storage service.

const assetId = '00000000-0000-0000-0000-000000000000';

const assetMetadata = await room.storage.getMetadata(assetId);

The following options are available:

ArgumentDescriptionType
1Asset ID: The id of the asset to be retrieved. This will be in uuid format.string

room.storage.getSrcUrl()

  • Requires "storage" permission

Synchronous method used to retrieve the src url for a file uploaded to a room's cloud storage service.

const src = room.storage.getSrcUrl();

Returns formatted url for the asset to be retrieved, with an authentication token.

By default, all assets are private and require authentication to access. A user with the "storage" permission for the given room can access the asset by providing an authentication token.

The src url of an asset will look something like this...

https://storage.prod.relaybox-services.net/assets/00000000-0000-0000-0000-000000000000?token=aaa.bbb.ccc

Example:

The example below retrives metadata for a file uploaded to a room's cloud storage service.

const assetId = '00000000-0000-0000-0000-000000000000';

const assetSrcUrl = room.storage.getSrcUrl(assetId);

...

<img src={assetSrcUrl} alt="Asset" />

The following options are available:

ArgumentDescriptionType
1Asset ID: The id of the asset to be retrieved. This will be in uuid format.string

    On this page