Chat.Client

You can use the Client object to build a messaging system into the browser.

Example usage:

import { Chat } from '@signalwire/js'

const chatClient = new Chat.Client({
  token: '<your_chat_token>',  // get this from the REST APIs
})

await chatClient.subscribe([ 'mychannel1', 'mychannel2' ])

chatClient.on('message', (message) => {
  console.log("Received", message.content,
              "on", message.channel,
              "at", message.publishedAt)
})

await chatClient.publish({
  channel: 'mychannel1',
  content: 'hello world'
})

Events

Please see ClientApiEvents for the list of events emitted by a chat Client object.

Constructors

constructor

new Client(chatOptions)

Creates a new Chat client.

Parameters

NameTypeDescription
chatOptionsObject-
chatOptions.tokenstring

SignalWire Chat token (you can get one with the REST APIs)

Example

import { Chat } from '@signalwire/js'

const chatClient = new Chat.Client({
  token: '<your_chat_token>',
})

Methods

getMemberState

getMemberState(params): Promise<{ channels: Record<string, ChatChannelState> }>

Returns the states of a member in the specified channels.

Parameters

NameTypeDescription
paramsObject-
params.channels?string | string[]

Channels for which to get the state.

params.memberIdstring

Id of the member for which to get the state.

Returns

Promise<{ channels: Record<string, ChatChannelState> }>

Example

const s = await chatClient.getMemberState({
  channels: ['chan1', 'chan2'],
  memberId: 'my-member-id'
})

s.channels.length;  // 2
s.channels.chan1.state;  // the state object for chan1

getMembers

getMembers(params): Promise<{ members: ChatMemberEntity[] }>

Returns the list of members in the given channel.

Parameters

NameTypeDescription
paramsObject-
params.channelstring

The channel for which to get the list of members.

Returns

Promise<{ members: ChatMemberEntity[] }>

Example

const m = await chatClient.getMembers({ channel: 'my-channel' })

m.members.length;  // 7
m.members[0];  // { id: ..., channel: ..., state: ... }

getMessages

getMessages(params): Promise<{ cursor: PagingCursor ; messages: ChatMessageEntity[] }>

Returns the list of messages that were sent to the specified channel.

Parameters

NameTypeDescription
paramsObject-
params.channelstring

Channel for which to retrieve the messages.

params.cursor?PagingCursor

Cursor for pagination.

Returns

Promise<{ cursor: PagingCursor ; messages: ChatMessageEntity[] }>

Example

const m = await chatClient.getMessages({ channel: 'chan1' })

m.messages.length;  // 23
m.messages[0];  // the most recent message
m.messages[0].member;  // the sender
m.messages[0].content;  // the content
m.messages[0].meta;  // the metadata (if any)

m.cursor.next;  // if not null, there are more messages.

// Get the next page using the cursor
const next = await chatClient.getMessages({
  channel: 'chan1',
  cursor: {
    after: m.cursor.after
  }
})

off

off<T>(event, fn?): EmitterContract<ClientApiEvents>

Type parameters

NameType
Textends keyof ClientApiEvents

Parameters

NameType
eventT
fn?(...args: ArgumentMap<ClientApiEvents>[Extract<T, keyof ClientApiEvents>]) => void

Returns

EmitterContract<ClientApiEvents>


on

on<T>(event, fn): EmitterContract<ClientApiEvents>

Type parameters

NameType
Textends keyof ClientApiEvents

Parameters

NameType
eventT
fn(...args: ArgumentMap<ClientApiEvents>[Extract<T, keyof ClientApiEvents>]) => void

Returns

EmitterContract<ClientApiEvents>


once

once<T>(event, fn): EmitterContract<ClientApiEvents>

Type parameters

NameType
Textends keyof ClientApiEvents

Parameters

NameType
eventT
fn(...args: ArgumentMap<ClientApiEvents>[Extract<T, keyof ClientApiEvents>]) => void

Returns

EmitterContract<ClientApiEvents>


publish

publish(params): Promise<void>

Publish a message into the specified channel.

Parameters

NameTypeDescription
paramsObject-
params.channelstring

Channel in which to send the message.

params.contentany

The message to send. This can be any JSON-serializable object.

params.meta?Record<any, any>

Metadata associated with the message. There are no requirements on the content of metadata.

Returns

Promise<void>

Examples

Publishing a message as a string:

await chatClient.publish({
  channel: 'my-channel',
  content: 'Hello, world.'
})

Publishing a message as an object:

await chatClient.publish({
  channel: 'my-channel',
  content: {
    field_one: 'value_one',
    field_two: 'value_two',
  }
})

removeAllListeners

removeAllListeners<T>(event?): EmitterContract<ClientApiEvents>

Type parameters

NameType
Textends keyof ClientApiEvents

Parameters

NameType
event?T

Returns

EmitterContract<ClientApiEvents>


setMemberState

setMemberState(params): Promise<void>

Sets a state object for a member, for the specified channels. The previous state object will be completely replaced.

Parameters

NameTypeDescription
paramsObject-
params.channelsstring | string[]

Channels for which to set the state.

params.memberIdstring

Id of the member to affect. If not provided, defaults to the current member.

params.stateRecord<any, any>

The state to set. There are no requirements on the content of the state.

Returns

Promise<void>

Example

await chatClient.setMemberState({
  channels: ['chan1', 'chan2'],
  state: {
    online: true,
    typing: false
  }
})

subscribe

subscribe(channels): Promise<void>

List of channels for which you want to receive messages. You can only subscribe to those channels for which your token has read permission.

Note that the subscribe function is idempotent, and calling it again with a different set of channels will not unsubscribe you from the old ones. To unsubscribe, use unsubscribe.

Parameters

NameTypeDescription
channelsstring | string[]

the channels to subscribe to, either in the form of a string (for one channel) or an array of strings.

Returns

Promise<void>

Example

const chatClient = new Chat.Client({
  token: '<your chat token>'
})

chatClient.on('message', m => console.log(m))

await chatClient.subscribe("my-channel")
await chatClient.subscribe(["chan-2", "chan-3"])

unsubscribe

unsubscribe(channels): Promise<void>

List of channels from which you want to unsubscribe.

Parameters

NameTypeDescription
channelsstring | string[]

the channels to unsubscribe from, either in the form of a string (for one channel) or an array of strings.

Returns

Promise<void>

Example

await chatClient.unsubscribe("my-channel")
await chatClient.unsubscribe(["chan-2", "chan-3"])

updateToken

updateToken(token): Promise<void>

Replaces the token used by the client with a new one. You can use this method to replace the token when for example it is expiring, in order to keep the session alive.

The new token can contain different channels from the previous one. In that case, you will need to subscribe to the new channels if you want to receive messages for those. Channels that were in the previous token but are not in the new one will get unsubscribed automatically.

Parameters

NameTypeDescription
tokenstring

the new token.

Returns

Promise<void>

Example

const chatClient = new Chat.Client({
  token: '<your chat token>'
})

chatClient.on('session.expiring', async () => {
  const newToken = await fetchNewToken(..)

  await chatClient.updateToken(newToken)
})