Node.js server SDK

Node.js SDK for the Chatkit service.

Setting Up

Installing

Via npm:

npm install @pusher/chatkit-server --save

Via yarn:

yarn add @pusher/chatkit-server

Importing

If you’re using a transpiler or a sufficiently up-to-date browser then you can import the SDK like this:

import Chatkit from '@pusher/chatkit-server';

If not, then you can import it using the standard require syntax:

const Chatkit = require('@pusher/chatkit-server');

Instantiating the Client object

The Client constructor takes an options object with the following properties:

Example
1
2
3
4
const chatkit = new Chatkit.default({
  instanceLocator: YOUR_INSTANCE_LOCATOR,
  key: YOUR_KEY,
})

SDK Usage

Unless otherwise specified, a promise will be returned from each function call made using the SDK.

All functions take a single object as the expected argument. The expected shape of the object is described in the documentation below.

As such, a typical usage would look something like this:

1
2
3
4
5
6
7
8
9
chatkit.createUser({
  id: 'userId',
  name: 'Some Name',
})
  .then(() => {
    console.log('User created successfully');
  }).catch((err) => {
    console.log(err);
  });

Users

Creating a User

Create a new User to use with the Chatkit service.

Usage

The createUser method takes a single object of the form:

  • id (string, required): An ID that uniquely identifies a User in the Chatkit service.
  • name (string, required): A name assigned to the user.
  • avatarURL (string, optional): Valid URL pointing to an image.
  • customData (map, optional): Map of user related properties.
1
2
3
4
5
6
7
8
9
chatkit.createUser({
  id: 'userId',
  name: 'Some name',
})
  .then(() => {
    console.log('User created successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

Returns a user object if the user was successfully created

1
2
3
4
5
6
{
  "id": "userId",
  "name": "user",
  "created_at": "2017-03-23T11:36:42Z",
  "updated_at": "2017-03-23T11:36:42Z"
}

Batch creating Users

Create multiple Chatkit users.

Usage

The createUsers method takes a single object of the form:

  • users (Array, required): Array of user objects.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const usersToCreate = [
  {
    id: 'user1',
    name: 'User 1',
  },
  {
    id: 'user2',
    name: 'User 2',
  }
];

chatkit.createUsers({ users: usersToCreate })
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

A JSON array containing a list of created user objects

1
2
3
4
5
6
7
8
9
10
11
12
{
  "id": "user1",
  "name": "User 1",
  "created_at": "2017-03-23T11:36:42Z",
  "updated_at": "2017-03-23T11:36:42Z"
},
{
  "id": "user2",
  "name": "User 2",
  "created_at": "2017-03-23T11:36:42Z",
  "updated_at": "2017-03-23T11:36:42Z"
}

Updating a User

Update the metadata attached to a given user.

Usage

The updateUser method takes a single object containing the attributes that should be updated. You can also attach custom metadata to a user using the customData attribute.

  • id (string, required): Unique ID to match the user to be updated.
  • name (string, optional): An updated name for the user
  • avatarURL (string, optional): An updated avatar URL for the user
  • customData (object, optional): Updated custom data for the user
1
2
3
4
5
6
7
8
9
10
11
12
13
chatkit.updateUser({
  id: 'someId',
  name: 'New Name',
  avatarURL: 'https://some.url',
  customData: {
    age: 21,
  },
})
  .then(() => {
    console.log('User updated successfully');
  }).catch((err) => {
    console.log(err);
  });

Deleting a User

Delete a previously created User.

Usage

The asyncDeleteUser method takes a single object of the form:

  • userId (string, required): Unique ID to match the user to be deleted.
1
2
3
4
5
chatkit.asyncDeleteUser({ userId: "someId" })
  .then(({ id: jobId }) => console.log("Created async delete job for user")
  .catch(err => {
    console.error(err)
  })

Get delete status of a User

The getDeleteStatus method takes a single object of the form:

  • jobId (string, required): Unique ID to match the job to be queried.
1
2
3
4
5
6
7
chatkit.getDeleteStatus({ jobId: "someId" })
  .then(res => {
    console.log(`delete user status: ${res.status}`)
  })
  .catch(err => {
    console.error(err)
  });
Response

The response body returns the id and status of a delete job. The status can be one of "in_progress", "completed" or "failed".

1
2
3
4
{
  "id": "some_id",
  "status": "in_progress"
}

Authenticate a User

Generate a HTTP status and body appropriate to use as the response of an authentication request from one of your clients. e.g.

1
2
3
4
5
6
7
8
9
10
// Example using Express

app.post('/auth', (req, res) => {
  const authData = chatkit.authenticate({
    userId: req.query.user_id
  });

  res.status(authData.status)
     .send(authData.body);
})

Get a User

Get a single user by ID. Takes an object with an id property.

1
2
3
4
5
chatkit.getUser({
  id: 'callum',
})
  .then(user => console.log('got a user', user))
  .catch(err => console.error(err))

Get Users

The getUsers function returns users, orederd by creation date from oldest to newest. Takes an object with the following properties.

  • fromTimestamp (string, optional) return users newer than this
  • limit (number, optional) return at most this many users
1
2
3
4
5
6
chatkit.getUsers()
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An array of JSON objects

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[
  {
    "id": "gary",
    "name": "Gary McGaryface",
    "avatar_url": "https://gravatar.com/img/8819",
    "custom_data": {
    "email": "a@b.com"
  },
    "created_at": "2017-03-23T11:36:42Z",
    "updated_at": "2017-03-23T11:36:42Z"
  },
  {
    "id": "john",
    "name": "John Doe",
    "avatar_url": "https://gravatar.com/img/8819",
    "custom_data": {
    "email": "a@b.com"
  },
    "created_at": "2017-03-23T11:36:42Z",
    "updated_at": "2017-03-23T11:36:42Z"
  }
]

Get Users by ID

Supply an array of user IDs, get back an array of Users.

1
2
3
4
5
chatkit.getUsersById({
  userIds: ['alice', 'bob', 'carol', 'dave'],
})
  .then(users => console.log('got users', users))
  .catch(err => console.error(err))

Rooms

Create a Room

1
2
3
4
5
6
7
8
9
10
11
chatkit.createRoom({
  id: 'my-room',
  creatorId: 'userId',
  name: 'my room',
  customData: { foo: 42 },
})
  .then(() => {
    console.log('Room created successfully');
  }).catch((err) => {
    console.log(err);
  });

Create a new public or private room.

Usage

createRoom takes an object of the form:

  • id (string, optional): The ID to assign to the room. If this is omitted, we&squo;ll provide a UUID.
  • creatorId (string, required): The ID of the user who is creating the room.
  • name (string, required): The name of the room.
  • isPrivate (boolean, optional): Whether or not the room is to be private. Defaults to false.
  • userIds (array, optional): An array of user IDs to be added as members of the room.
  • customData (object, optional) Arbitrary custom data to be attached to the room.
Response

An object that looks like this:

1
2
3
4
5
6
7
8
9
10
{
  id: '123',
  created_by_id: 'a_user',
  name: 'my room',
  private: false,
  created_at: '2017-11-10T14:57:46Z',
  updated_at: '2017-11-10T14:57:46Z',
  member_user_ids: [ 'some_other_user', 'a_user' ],
  custom_data: { foo: 42 },
}

Update a Room

updateRoom modifies a room’s name or privacy. Takes an object with the following properties:

  • id (string, required): The ID of the room to be updated.
  • name (string, optional): The name of the room.
  • isPrivate (boolean, optional): Whether or not the room is to be private. Defaults to false.
  • customData (object, optional) Arbitrary custom data to be attached to the room.
1
2
3
4
5
6
7
8
chatkit.updateRoom({
  id: roomToUpdate.id,
  name: 'Members only',
  isPrivate: true,
  customData: { bar: 'baz' },
})
  .then(() => console.log('room successfully updated'))
  .catch(err => console.error(err))

Add users to a room

addUsersToRoom adds users as members of a room. Takes an object with the following parameters

  • roomId (string, required) The room to add users to
  • userIds ([]string, required) The users to add
1
2
3
4
5
6
chatkit.addUsersToRoom({
  roomId: room.id,
  userIds: ['alice', 'bob']
})
  .then(() => console.log('added'))
  .catch(err => console.error(err))

Currently the maximum number of users that can be a member of the same room is 500. You can see the full list of limits detailed here.

Remove users from a room

removeUsersFromRoom removes users with the given ID from a room. Takes an object with the following parameters

  • roomId (string, required) The room to remove users from
  • userIds ([]string, required) The users to remove
1
2
3
4
5
6
chatkit.removeUsersFromRoom({
  roomId: room.id,
  userIds: ['alice', 'bob']
})
  .then(() => console.log('removed'))
  .catch(err => console.error(err))

Delete a Room

asyncDeleteRoom irreversibly deletes the room, along with all its messages and metadata. Takes an object with a single roomId parameter: the ID of the room to be deleted.

1
2
3
4
5
6
chatkit.asyncDeleteRoom({
  roomId: roomToDelete.id
})
  .then(({ id: jobId }) => console.log("Created async delete job for room")
  )
  .catch(err => console.error(err))

Get delete status of a Room

The getDeleteStatus method takes a single object of the form:

  • jobId (string, required): Unique ID to match the job to be queried.
1
2
3
4
5
6
7
chatkit.getDeleteStatus({ jobId: "someId" })
  .then(res => {
    console.log(`delete user status: ${res.status}`)
  })
  .catch(err => {
    console.log(err)
  })
Response

The response body returns the id and status of a delete job. The status can be one of "in_progress", "completed" or "failed".

1
2
3
4
{
  "id": "some_id",
  "status": "in_progress"
}

Get a Room

Fetch a room by its ID. Takes an object with a single roomId parameter.

1
2
3
4
5
chatkit.getRoom({
  roomId: "123",
})
  .then(room => console.log('got room', room))
  .catch(err => console.error(err))

Get Rooms

getRooms fetches rooms, ordered by ID, in pages of 100 at a time. Takes an object with the following properties:

  • fromId (string, optional) starting ID of the range of rooms (exclusive)
  • includePrivate (boolean, optional) If true private rooms will be included in the response, otherwise they will be filtered out.
1
2
3
chatkit.getRooms({})
  .then(rooms => console.log('got rooms', rooms))
  .catch(err => console.error(err))

Get User Joinable Rooms

Get a list of rooms that the user can join.

Usage

The getUserJoinableRooms function takes an object of the form:

  • userId (String, required): ID of the user for whom rooms should be retrieved
1
2
3
4
5
6
7
8
chatkit.getUserJoinableRooms({
  userId: 'user1'
})
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An array of JSON objects

1
2
3
4
5
6
7
8
9
10
11
[
  {
    "id": "1",
    "created_by_id": "user2",
    "name": "mycoolroom",
    "private": false,
    "created_at": "2017-03-23T11:36:42Z",
    "updated_at": "2017-03-23T11:36:42Z",
    "member_user_ids":["user3", "user4"]
  }
]

Get User Rooms

Get a list of rooms that the user is a member of.

Usage

The getUserRooms function takes an object of the form:

  • userId (String, required): ID of the user for whom rooms should be retrieved
1
2
3
4
5
6
7
8
chatkit.getUserRooms({
  userId: 'user1',
})
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An array of JSON objects

1
2
3
4
5
6
7
8
9
10
11
12
13
[
  {
    "id": "1",
    "created_by_id": "user2",
    "name": "mycoolroom",
    "private": false,
    "created_at": "2017-03-23T11:36:42Z",
    "updated_at": "2017-03-23T11:36:42Z",
    "member_user_ids":["user3", "user4"],
    "unread_count": 1,
    "last_message_at": "2017-03-23T11:36:42Z"
  }
]

Messages

Send a message

There are two methods to send messages. In the simplest case you can send plain text messages with sendSimpleMessage. Takes an object of the form:

  • userId (string, required) the ID of the user to send the message as
  • roomId (string, required) the ID of the room to send the message to
  • text (string, required) the content of the message
1
2
3
4
5
6
7
chatkit.sendSimpleMessage({
  userId: 'alice',
  roomId: '123',
  text: 'hello!',
})
  .then(res => console.log('sent message with id', res.id))
  .catch(err => console.error(err))

For more complex messages you should use sendMultipartMessage instead. Takes an object of the form:

  • userId (string, required) the ID of the user to send the message as
  • roomId (string, required) the ID of the room to send the message to
  • parts (array, required) the parts composing the message.

Where each part is one of the following:

An inline part.

AttributeTypeDescription
typestringThe MIME type of the content.
contentstringThe string content of the part.

A URL part.

AttributeTypeDescription
typestringThe MIME type of the resource that the URL points to.
urlstringA URL.

An attachment part.

AttributeTypeDescription
typestringThe MIME type of the attachment.
fileBufferA Buffer – e.g. as returned from readFile.
namestringThe name of the attached file. (Optional.)
customDataanyArbitrary custom data to associate with the file. (Optional.)

For example, sending a message consisting of three parts, one of each of the above:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
fs.readFile("tiny-pig.gif", (err, data) => {
  if (err) {
    console.error(err)
  } else {
    chatkit
      .sendMultipartMessage({
        roomId: process.argv[2],
        userId: "alice",
        parts: [
          {
            type: "text/plain",
            content: "see attached",
          },
          {
            type: "audio/ogg",
            url: "https://example.com/oink.ogg",
          },
          {
            type: "image/gif",
            file: data,
            customData: { foo: "bar" },
          },
        ],
      })
      .then(id => console.log("sent", id))
      .catch(console.error)
  }
})

Fetch a single message from a room

fetchMultipartMessage fetches a message from a room. Takes an object with the following properties:

  • roomId (string, required) the ID of the room to get messages from
  • messageId (string, required) the ID of the message to fetch

1
2
3
4
5
6
7
8
chatkit.fetchMultipartMessage({
  roomId: room.id,
  messageId: "123456"
})
.then(message => {
  console.log(message)
})
.catch(err => console.error(err))

Fetch messages from a room

fetchMultipartMessages fetches the messages from a room. Messages are returned in pages of at most 100 at a time. Takes an object with the following properties:

  • roomId (string, required) the ID of the room to get messages from
  • direction (string, optional) direction to page back through messages – one of "older" or "newer"
  • initialId (string, optional) starting ID of the range of messages (exclusive)
  • limit (number, optional) number of messages to return in a single page (defaults to 20, maximum 100)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
chatkit.fetchMultipartMessages({
  roomId: room.id,
  limit: 10,
})
  .then(messages => {
    console.log('got last 10 messages')
    for (let m of messages) {
      renderMessage(m)
    }
    return chatkit.fetchMultipartMessages({
      roomId: room.id,
      initialId: res[messages.length - 1].id,
    })
  })
  .then(moreMessages => {
    console.log('got the next 10 messages before them')
    for (let m of moreMessages) {
      renderMessage(m)
    }
  })
  .catch(err => console.error(err))

fetchMultipartMessages replaces its deprecated predecessor getRoomMessages. The latter functions similarly but return the legacy message type.

Delete a Message

deleteMessage irreversibly deletes the message. Takes an object with roomId and messageId parameters.

1
2
3
4
5
6
chatkit.deleteMessage({
  roomId: roomToDeleteMessageFrom.id
  messageId: messageToDelete.id
})
  .then(() => console.log('gone forever'))
  .catch(err => console.error(err))

Edit a message

There are two methods to edit messages. editSimpleMessageand editMultipartMessage.

These methods can be used to:

  • Modify the text content of one or many parts of a message
  • Add attachments to one or many parts of a message
  • Remove attachments from one of many parts of a message
  • Change the sender id of a message (supplied in the authentication token)

This endpoint cannot:

  • Move a message between rooms
  • Change the id of a message

After a message is edited:

  • Connected clients will receive an event containing the new message data
  • Fetches will return the edited message with modified updated_at,user_id and parts fields.
  • Attachments that have been lost are deleted from storage

Make sure edit requests include all parts you wish to retain. Missing text, attachments or parts will be dropped.

In the simplest case you can edit an existing message to a plain text message witheditSimpleMessage. This method first takes two parameters that identify the target message. These are the roomId and messageId. These properties are not modifiable. The last parameter is an object which contains the editable properties of the message. The parameters in this body have replace semantics This object has the form:

  • userId (string, required) the ID of the user to send the message as
  • text (string, required) the content of the message
1
2
3
4
chatkit.editSimpleMessage('room-123', 42, {
  userId: 'alice',
  text: 'hello!',
})

For more complex messages you should use editMultipartMessage. This method first takes two parameters that identify the target message. These are the roomId and messageId. These properties are not modifiable. The last parameter is an object which contains the editable properties of the message. The parameters in this body have replace semantics. This object has the form:

  • userId (string, required) the ID of the user to send the message as
  • parts (array, required) the parts composing the message

Where each part is one of the following:

An inline part.

AttributeTypeDescription
typestringThe MIME type of the content.
contentstringThe string content of the part.

A URL part.

AttributeTypeDescription
typestringThe MIME type of the resource that the URL points to.
urlstringA URL.

An attachment part.

AttributeTypeDescription
typestringThe MIME type of the attachment.
fileBufferA Buffer – e.g. as returned from readFile.
namestringThe name of the attached file. (Optional.)
customDataanyArbitrary custom data to associate with the file. (Optional.)

Example: Correct a typo on a single part message

Given:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "id": 20,
  "user_id": "alice",
  "room_id": "1",
  "parts": [
    {
      "type": "text/plain",
      "content": "Hello wrold!"
    }
  ],
  "created_at":"2019-12-18T11:36:42Z",
  "updated_at":"2019-12-18T11:36:42Z"
}}
Calling:
chatkit.editMultipartMessage("1", 20, {
  userId: "alice",
  parts: [
    {
      type: "text/plain",
      content: "Hello world!",
    },
  ]
})
Results in:
1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "id": 20,
  "user_id": "alice",
  "room_id": "1",
  "parts": [
    {
      "type": "text/plain",
      "content": "Hello world!"
    }
  ],
  "created_at":"2019-12-18T11:36:42Z",
  "updated_at":"2019-12-18T11:37:00Z"
}}
Note the updated_at has changed.

Example: Upload a missing attachment to an existing message

Given:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "id": 40,
  "user_id": "bob",
  "room_id": "2",
  "parts": [
    {
      "type": "text/plain",
      "content": "See attachment:"
    }
  ],
  "created_at":"2019-12-18T11:36:42Z",
  "updated_at":"2019-12-18T11:36:42Z"
}}
Call edit message with the original part and a new attachment part:
chatkit.editMultipartMessage("2", 40, {
  userId: "bob",
  parts: [
    {
      type: "text/plain",
      content: "See attachment:",
    },
    {
      type: "application/pdf",
      file: data,
    }
  ]
})
Results in:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
{
  "id": 40,
  "user_id": "bob",
  "room_id": "2",
  "parts": [
    {
      "type": "text/plain",
      "content": "See attachment:"
    },
    {
      "type": "application/pdf",
      "attachment": {
        "id": "793c8a94-1702-4b7b-92aa-62f3be1a8efb",
        "download_url": "https://example.download.url/793c8a94-1702-4b7b-92aa-62f3be1a8efb",
        "refresh_url": "https://example.refresh.url/793c8a94-1702-4b7b-92aa-62f3be1a8efb",
        "expiration": "2019-02-12T17:29:22Z",
        "name": "super-interesting-document.pdf",
        "size": 1234,
        "custom_data": {
          "foo": "bar"
        }
      }
    }
  ],
  "created_at":"2019-12-18T11:36:42Z",
  "updated_at":"2019-12-18T11:37:00Z"
}}

Example: Drop a part from a message

Given:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
  "id": 60,
  "user_id": "charlie",
  "room_id": "3",
  "parts": [
    {
      "type": "text/plain",
      "content": "Original first part"
    },
    {
      "type": "text/plain",
      "content": "Original second part to drop"
    },
    {
      "type": "text/plain",
      "content": "Original third part"
    }
  ],
  "created_at":"2019-12-18T11:36:42Z",
  "updated_at":"2019-12-18T11:36:42Z"
}}
Call the edit endpoint with parts to be retained:
chatkit.editMultipartMessage("3", 60, {
  userId: "charlie",
  parts: [
    {
      type: "text/plain",
      content: "Edited first part",
    },
    {
      "type": "text/plain",
      "content": "Edited second part"
    }
  ]
})
Results in:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
  "id": 60,
  "user_id": "charlie",
  "room_id": "3",
  "parts": [
    {
      "type": "text/plain",
      "content": "Edited first part"
    },
    {
      "type": "text/plain",
      "content": "Edited second part"
    },
  ],
  "created_at":"2019-12-18T11:36:42Z",
  "updated_at":"2019-12-18T11:37:00Z"
}}
Note that both the number of parts and their content has changed.

Example: Remove an attachment from a message

Given:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
{
  "id": 80,
  "user_id": "dave",
  "room_id": "4",
  "parts": [
    {
      "type": "text/plain",
      "content": "Accidental attachment included:"
    },
    {
      "type": "application/pdf",
      "attachment": {
        "id": "793c8a94-1702-4b7b-92aa-62f3be1a8efb",
      }
    }
  ],
  "created_at":"2019-12-18T11:36:42Z",
  "updated_at":"2019-12-18T11:36:42Z"
}}
Calling the edit endpoint without the attachment:
chatkit.editMultipartMessage("4", 80, {
  userId: "dave",
  parts: [
    {
      type: "text/plain",
      content: "No longer any attachment included",
    },
  ]
})
Results in:
1
2
3
4
5
6
7
8
9
10
11
12
13
{
  "id": 80,
  "user_id": "dave",
  "room_id": "4",
  "parts": [
    {
      "type": "text/plain",
      "content": "No longer any attachment included"
    }
  ],
  "created_at":"2019-12-18T11:36:42Z",
  "updated_at":"2019-12-18T11:37:00Z"
}}
Note:
  • The attachment is removed from the message
  • The attachment is removed from storage

Read Cursors

Set a read cursor

setReadCursor sets the read cursor for the given user and room to the given position (the latest read message ID). Takes an object with the following properties

  • userId (string, required) The ID of the user to set the cursor for.
  • roomId (string, required) The ID of the room to set the cursor for.
  • position (number, required) The latest read message ID
1
2
3
4
5
6
7
8
chatkit
  .setReadCursor({
    userId: user.id,
    roomId: room.id,
    position: 42,
  })
  .then(() => console.log('done!'))
  .catch(err => console.error(err))

Get a read cursor

getReadCursor gets the read cursor for the given user and room. Takes an object with the following properties

  • userId (string, required) The ID of the user to get the cursor for.
  • roomId (string, required) The ID of the room to get the cursor for.
1
2
3
4
5
6
7
chatkit
  .getReadCursor({
    userId: user.id,
    roomId: room.id,
  })
  .then(cursor => console.log('got cursor', cursor))
  .catch(err => console.error(err))

Get all of a user’s read cursors

getReadCursorsForUser gets all of the given user’s read cursors. Takes an object with the following properties

  • userId (string, required) The ID of the user to get the cursors for.
1
2
3
4
5
6
chatkit
  .getReadCursorsForUser({
    userId: user.id,
  })
  .then(cursors => console.log('got cursors', cursors))
  .catch(err => console.error(err))

Get all of the read cursors for a room

getReadCursorsForRoom gets all of the read cursors for the given room. Takes an object with the following properties

  • roomId (string, required) The ID of the room to get the cursors for.
1
2
3
4
5
chatkit.getReadCursorsForRoom({
  roomId: room.id,
})
  .then(cursors => console.log('got cursors', cursors))
  .catch(err => console.error(err))

Roles and Permissions

Creating a Role with the Room scope

Create a Role intended for use within the scope of a room identified by its ID.

Usage

createRoomRole takes an object of the form:

  • name (string, required): A unique name for the role.
  • permissions (array, required): A list of permissions outlined in the authentication docs.
1
2
3
4
5
6
7
8
9
chatkit.createRoomRole({
  name: 'mycoolroomrole',
  permissions: ['room:join'],
})
  .then(() => {
    console.log('Room role created successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned.

Creating a Role with the Global scope

Create a Role intended for use globally.

Usage

createGlobalRole takes an object of the form:

  • name (string, required): A unique name for the role.
  • permissions (array, required): A list of permissions outlined in the authentication docs.
1
2
3
4
5
6
7
8
9
chatkit.createGlobalRole({
  name: 'mycoolglboalrole',
  permissions: ['room:join'],
})
  .then(() => {
    console.log('Global role created successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned.

Deleting a Room scoped Role

Delete a room scoped role.

Usage

deleteRoomRole takes an object of the form:

  • name (string, required): Role name by which the role is identified.
1
2
3
4
5
6
chatkit.deleteRoomRole({ name: 'mycoolroomrole' })
  .then(() => {
    console.log('Room role deleted successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned.

Deleting a Global scoped Role

Delete a global scoped role.

Usage

deleteGlobalRole takes an object of the form:

  • name (string, required): Role name by which the role is identified.
1
2
3
4
5
6
chatkit.deleteGlobalRole({ name: 'mycoolglobalrole' })
  .then(() => {
    console.log('Global role deleted successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned.

Assigning a Room scoped role to a User

Assign a room scoped role to a User for a given room ID.

Usage

assignRoomRoleToUser takes an object of the form:

  • userId (string, required): User ID to assign the role to.
  • name (string, required): Name of the role to be assigned to the user.
  • roomId (integer, required): Room ID to which the role is bound to.
1
2
3
4
5
6
7
8
9
10
chatkit.assignRoomRoleToUser({
  userId: 'userId',
  name: 'mycoolroomrole',
  roomId: '234',
})
  .then(() => {
    console.log('Assigned room role successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned

Assigning a Global scoped role a User

Assign a role scoped globally to a User.

Usage

assignGlobalRoleToUser takes an object of the form:

  • userId (string, required): User ID to assign the role to.
  • name (string, required): Name of the role to be assigned to the user.
1
2
3
4
5
6
7
8
9
chatkit.assignGlobalRoleToUser({
  userId: 'userId',
  name: 'mycoolglobalrole',
})
  .then(() => {
    console.log('Assigned global role successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned

Removing a Room scoped role for a User

Un-assign a room scoped role from a User.

Usage

removeRoomRoleForUser takes an object of the form:

  • userId (string, required): User ID the role was assigned to.
  • roomId (string, required): Room ID of the role.
1
2
3
4
5
6
7
8
9
chatkit.removeRoomRoleForUser({
  userId: 'userId',
  roomId: 'mycoolroomrole',
})
  .then(() => {
    console.log('Removed room role successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned.

Removing a Global scoped role for a User

Un-assign a global scoped role from a User.

Usage

removeGlobalRoleForUser takes an object of the form:

  • userId (string, required): User ID the role was assigned to.
1
2
3
4
5
6
chatkit.removeGlobalRoleForUser({ userId: 'userId' })
  .then(() => {
    console.log('Removed global role successfully');
  }).catch((err) => {
    console.log(err);
  });
Response

No response body is returned.

List all Roles for an Instance

Fetch all roles created for an instance.

Usage

getRoles does not take any arguments.

1
2
3
4
5
6
chatkit.getRoles()
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An array of JSON objects

1
2
3
4
5
6
7
8
9
10
11
12
[
  {
    "role_name": "mycoolglobalrole",
    "permissions": ["room:join"],
    "scope_name": "global"
  },
  {
    "role_name": "mycoolroomrole",
    "permissions": ["room:update"],
    "scope_name": "room"
  }
]

List Roles for a User

Fetch roles assigned to a user.

Usage

getUserRoles takes an object of the form:

  • userId (string, required): User ID to which roles are assigned.
1
2
3
4
5
6
chatkit.getUserRoles({ userId: 'userId' })
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An array of JSON objects

1
2
3
4
5
6
7
8
9
10
11
[
  {
    "role_name": "mycoolglobalrole",
    "permissions": ["room:join"]
  },
  {
    "role_name": "mycoolroomrole",
    "permissions": ["room:update"],
    "room_id": 234
  }
]

List Permissions associated with a Room scoped Role

Fetch the list of permissions assigned to a room scoped role.

Usage

getPermissionsForRoomRole takes an object of the form:

  • name (string, required): Name of the role with which permissions are associated.
1
2
3
4
5
6
7
8
chatkit.getPermissionsForRoomRole({
  name: 'mycoolroomrole'
})
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An Array of permission names

1
["room:update"]

List permissions associated with a Global scoped Role

Fetch the list of permissions assigned to a global role.

Usage

getPermissionsForGlobalRole takes an object of the form:

  • name (string, required): Name of the role with which permissions are associated.
1
2
3
4
5
6
7
8
chatkit.getPermissionsForGlobalRole({
  name: 'mycoolglobalrole'
})
  .then((res) => {
    console.log(res);
  }).catch((err) => {
    console.log(err);
  });
Response

An Array of permission names

1
["room:join"]

Update Permissions associated with a Room scoped Role

Update the list of permissions assigned to a room scoped role.

Usage

updatePermissionsForRoomRole takes an object of the form:

  • name (string, required): Name of the role with which permissions are associated.
  • permissionsToAdd ([]string, optional): The permissions to add to the role.
  • permissionsToRemove ([]string, optional): The permissions to remove from the role.
1
2
3
4
5
6
chatkit.updatePermissionsForRoomRole({
  name: 'mycoolroomrole',
  permissionsToAdd: ['room:update']
})
  .then(() => console.log('done!'))
  .catch(err => console.error(err))

Update permissions associated with a Global scoped Role

Update the list of permissions assigned to a global role.

Usage

updatePermissionsForGlobalRole takes an object of the form:

  • name (string, required): Name of the role with which permissions are associated.
  • permissionsToAdd ([]string, optional): The permissions to add to the role.
  • permissionsToRemove ([]string, optional): The permissions to remove from the role.
1
2
3
4
5
6
chatkit.updatePermissionsForGlobalRole({
  name: 'mycoolglobalrole',
  permissionsToRemove: ['room:update']
})
  .then(() => console.log('done!'))
  .catch(err => console.error(err))

Errors

Error responses returned by the API take the shape of an object which contains details of the error.

1
2
3
4
5
{
  "error": "unprocessable_entity/invalid_json_body",
  "error_description": "Failed to parse request body",
  "error_uri": "https://docs.pusher.com/errors/unprocessable_entity/invalid_json_body"
}