Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

amazon-ivs-chat-messaging

Package Overview
Dependencies
Maintainers
1
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

amazon-ivs-chat-messaging

The IVS Chat Messaging SDK makes it quick and easy to build excellent chat experience in your JavaScript or TypeScript app.

  • 1.0.1
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

IVS Chat Messaging SDK for JavaScript

The IVS Chat Messaging SDK makes it quick and easy to build excellent chat experience in your JavaScript or TypeScript app.

1. Table of contents

1.1. Getting Started

Before starting, you should be familiar with Getting Started with Amazon IVS Chat.

See also SDK Documentation.

1.1.1 Add the Package

$ npm install --save amazon-ivs-chat-messaging

or

$ yarn add amazon-ivs-chat-messaging

1.1.2 Set Up Your Backend

This integration requires endpoints on your server that talk to the Amazon IVS Chat API. Use the official AWS libraries for access to the Amazon IVS API from your server. These are accessible within several languages from the public packages; e.g. node.js, java, go.

Next, create a server endpoint that talks to the AWS IVS Chat CreateChatToken endpoint in order to create a chat token for chat users. You can follow our sample backend implementation as a reference.

1.1.3 Token provider function

Create an asynchronous token provider function that fetches chat token from your backend.

type ChatTokenProvider = () => Promise<ChatToken>;

Function should accept no parameters and return a Promise containing chat token object.

Chat token object should have following shape:

type ChatToken = {
  token: string;
  sessionExpirationTime?: Date;
  tokenExpirationTime?: Date;
}

This function is needed to instantiate ChatRoom object in the next step.

// You will need to fetch a fresh token each time this method is called by
// the IVS Chat Messaging SDK, since each token is only accepted once.
function tokenProvider(): Promise<ChatToken> {
  // Call you backend to fetch chat token from IVS Chat endpoint: 
  // e.g. const token = await appBackend.getChatToken()
  return {
    token: "<token>",
    sessionExpirationTime: new Date("<date-time>"),
    tokenExpirationTime: new Date("<date-time>")
  }
}

Note: you need to fill in <token> & <date-time> fields with proper data received from you backend.

2. Using the SDK

2.1. Initialize a Chat Room Instance

Create an instance of the ChatRoom class. It requires passing regionOrUrl, which is the AWS region in which your chat room is hosted, and tokenProvider which is the token fetching method created in the previous step.

import { ChatRoom } from 'amazon-ivs-chat-messaging';

const room = new ChatRoom({
  regionOrUrl: 'us-west-2',
  tokenProvider,
});

Next, you should subscribe for chat room events in order to receive lifecycle events, as well as receive messages & events delivered in the chat room.

/**
 * Called when room is establishing the initial connection or reestablishing
 * connection after socket failure/token expiration/etc
 */
const unsubscribeOnConnecting = room.addListener('connecting', () => { });

/** Called when connection has been established. */
const unsubscribeOnConnected = room.addListener('connect', () => { });

/** Called when a room has been disconnected. */
const unsubscribeOnDisconnected = room.addListener('disconnect', () => { });

/** Called when chat message has been received. */
const unsubscribeOnMessageReceived = room.addListener('message', (message) => {
  /* Example message: 
   * {
   *   id: "5OPsDdX18qcJ",
   *   sender: { userId: "user1" },
   *   content: "hello world",
   *   sendTime: new Date("2022-10-11T12:46:41.723Z"),
   *   requestId: "d1b511d8-d5ed-4346-b43f-49197c6e61de"
   * }
   */
});

/** Called when chat event has been received. */
const unsubscribeOnEventReceived = room.addListener('event', (event) => {
  /* Example event: 
   * { 
   *   id: "5OPsDdX18qcJ",
   *   eventName: "customEvent,
   *   sendTime: new Date("2022-10-11T12:46:41.723Z"),
   *   requestId: "d1b511d8-d5ed-4346-b43f-49197c6e61de",
   *   attributes: { "Custom Attribute": "Custom Attribute Value" }
   * }
   */
});

/** Called when `aws:DELETE_MESSAGE` system event has been received. */
const unsubscribeOnMessageDelete = room.addListener('messageDelete', (deleteMessageEvent) => {
  /* Example delete message event:
   * {
   *   id: "AYk6xKitV4On",
   *   messageId: "R1BLTDN84zEO",
   *   reason: "Spam",
   *   sendTime: new Date("2022-10-11T12:56:41.113Z"),
   *   requestId: "b379050a-2324-497b-9604-575cb5a9c5cd", 
   *   attributes: { MessageID: "R1BLTDN84zEO", Reason: "Spam" }
   * }
   */
});

/** Called when `aws:DISCONNECT_USER` system event has been received. */
const unsubscribeOnUserDisconnect = room.addListener('userDisconnect', (disconnectUserEvent) => {
  /* Example event payload: 
   * {
   *   id: "AYk6xKitV4On",
   *   userId": "R1BLTDN84zEO",
   *   reason": "Spam",
   *   sendTime": new Date("2022-10-11T12:56:41.113Z"),
   *   requestId": "b379050a-2324-497b-9604-575cb5a9c5cd",
   *   attributes": { UserId: "R1BLTDN84zEO", Reason: "Spam" }
   * }
   */
 });

The last step of the basic initialization is connecting to the chat room by establishing the WebSocket connection. In order to do that simply call a connect() method within the room instance.

room.connect();

The SDK will attempt to establish a connection to chat room encoded in chat token received from your server.

After calling connect() the room will transition into connecting state and will also emit a connecting event. When room successfully connects, it will transition into connected state and will emit a connect event.

In case of connection failure, which might happen either due to issues when fetching token or issues when connecting to WebSocket, the room will try to reconnect automatically up to number of times indicated by maxReconnectAttempts constructor parameter. During the reconnection attempts the room will be in connecting state and will not emit additional events. After exhausting the reconnect attempts the room will transition to disconnected state and will emit a disconnect event with relevant disconnect reason. In disconnected state room will no longer attempt to connect, you will need to call connect() again to trigger the connection process.

2.2. Perform Actions in a Chat Room

IVS Chat Messaging SDK offers user actions dedicated for sending messages, deleting messages and disconnecting other users. Those are available on the ChatRoom instance, and return Promise object that allows you to receive request confirmation or rejection.

2.2.1. Sending a Message

Note: that for this particular request you need to have a SEND_MESSAGE capacity encoded in your chat token.

To trigger a send-message request:

const request = new SendMessageRequest('Test Echo');
room.sendMessage(request);

If you are interested in receiving the confirmation or rejection of the request, you can await returned promise or use then() method:

try {
  const message = await room.sendMessage(request);
  // Message has been successfully send to chat room
} catch (error) {
  // Message request has been rejected, inspect `error` parameter for details.
}
2.2.2. Deleting a Message

Note: that for this particular request you need to have a DELETE_MESSAGE capacity encoded in your chat token.

To trigger a delete-message request:

const request = new DeleteMessageRequest(messageId, 'Reason for deletion');
room.deleteMessage(request);

If you're interested receiving confirmation or rejection of the request, you can await returned promise or use then() method:

try {
  const deleteMessageEvent = await room.deleteMessage(request);
  // Message has been successfully deleted from chat room
} catch (error) {
  // Delete message request has been rejected, inspect `error` parameter for details.
}
2.2.3. Disconnecting Another User

In order to disconnect another user for moderation purposes call disconnectUser() method.

Note: that for this particular request you need to have a DISCONNECT_USER capacity encoded in your chat token.

To disconnect another user for moderation purposes:

const request = new DisconnectUserRequest(userId, 'Reason for disconnecting user');
room.disconnectUser(request);

If you're interested receiving confirmation or rejection of the request, you can await returned promise or use then() method:

try {
  const disconnectUserEvent = await room.disconnectUser(request);
  // User has been successfully disconnected from the chat room
} catch (error) {
  // Disconnect user request has been rejected, inspect `error` parameter for details.
}

2.3. Disconnecting from a chat room

In order to close your connection to the chat room, call the disconnect() method on the room instance:

room.disconnect();

Calling this method will cause room to closes the underlying Web Socket in an orderly manner. The room instance will transition to a disconnected state and will emit a disconnect event, with disconnect reason being set to "clientDisconnect".

3. License

Amazon Interactive Video Service (IVS) (https://docs.aws.amazon.com/ivs/) Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.

Provided as AWS Content and subject to the AWS Customer Agreement (https://aws.amazon.com/agreement/) and any other agreement with AWS governing your use of AWS services.

See full license text for more information.

FAQs

Package last updated on 18 Oct 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc