Introduction

Welcome to the JavaScript SDK documentation. This guide will walk you through the integration process to add chat and presence monitoring capabilities to your application using our SDK.

Key Features
  • Real-time messaging within chatrooms.
  • Online presence tracking to see when users are online, or offline.
  • Support for both single and group chatrooms.
  • File uploads within messages.
  • Message receipts including user typing, message delivered, and message read notifications.
  • Extensive event handling to react to chat activities in real-time.
Getting Started
Prerequisites

Before integrating ezajil-js-sdk into your project, ensure you have:

  • Modern web browser with JavaScript enabled (e.g., Google Chrome, Mozilla Firefox, Safari, Edge).
  • Support for ES6 (ECMAScript 2015) or later for optimal SDK functionality.
  • An account registered on our platform.
Obtaining an API Key

Sign up on our platform and navigate to ezajil dashboard to create a new project. Upon creation, you will be provided with an endpoint and an API key required for authenticating your application.

Installation

To install the SDK in your project, run the following command in your project directory:

npm install ezajil-js-sdk --save
Basic usage
Authentication
API Key Usage

Effective authentication is crucial for the security and functionality of your application when integrating with our SDK.

It's essential to understand the proper use of API keys and the implementation of a token retrieval mechanism to maintain secure and uninterrupted sessions.

The API key is a sensitive piece of information that authenticates the communication between your application and our SaaS backend. It is paramount that the API key is not exposed in client-facing applications, such as browser apps, to prevent unauthorized access and potential security vulnerabilities.

  • The API key should be securely stored and used exclusively within your backend service.
  • Your backend service will use the API key to communicate with our SaaS backend to obtain access tokens, which are then used by the client application to interact with the SDK.
curl -X POST https://saasEndpoint/api/v1/users/auth
  -H "Content-Type: application/json"
  -H "api-key: yourApiKey"
  -d '{
    "userId": "userId",
    "screenName": "userScreenName"
    "avatarUrl": "userAvatarUrl"
    "email": "userEmail"
    "metadata": {...}
   }'
Implementing a Fetch Token Callback

To streamline the authentication process and handle token lifecycle management efficiently, we recommend implementing a fetch token callback. This callback is invoked automatically by the SDK whenever a new access token is required, either due to token expiration or when the current token is invalid.

Make sure to replace saasEndpoint with the actual value you obtained from the dashboard.
This example also assumes you're replacing userId, userScreenName, userAvatarUrl, userEmail, and userMetadata with the user information relevant to your application context.

import { Session, User } from 'ezajil-js-sdk';

const userMetadata = {...};
const currentUser = new User('userId', 'userScreenName', 'userAvatarUrl', 'userEmail', userMetadata);
const sdkConfig = { enableLogging: true };
const session = new Session('saasEndpoint', currentUser, sdkConfig);

session.setFetchTokenCallback(() => {
  // Make an HTTP request to YOUR backend service. This endpoint should be responsible for 
  // obtaining the access token from the authentication server using the API key securely stored 
  // on the server.
  const request = this.http.get<{ accessToken: string }>(`YOUR_BACKEND_ENDPOINT`, ...)
    .pipe(map(response => response.accessToken));
  return firstValueFrom(request);
});  
session.connect();
Create a Private 1-to-1 Chatroom

To initiate private communication between two users, you first need to create a private 1-to-1 chatroom.

This chatroom will be the space where the two users can exchange messages securely and privately.

The chatroomMetadata field allows you to attach key-value pairs to the chatroom, enabling you to store additional context-specific information. This metadata can be anything relevant to your application's context, like user roles, conversation topics, or initiation timestamps.

const chatroomMetadata = {...};
this.session.createSingleChatroom('chatroomName', 'participantId', chatroomMetadata)
  .then(chatroom => {
    // Handle chatroom
  })
  .catch(error => {
    // Handle the error, an APIError type with status, message, and details attributes
  });
Send Your First Message

To send a message, ensure you're authenticated and have a chatroom.

Here's how you can send a simple "Hello, World!" message.

const sentMessage = chatroom.sendChatMessage('Hello World!');
Subscribe to User's Presence Event

To monitor the presence status of other users, your application can subscribe to presence events. This feature allows you to track when users go online or offline, enabling real-time updates within your application.

By subscribing to a user's presence, you can receive immediate notifications about their online and offline status changes.

To subscribe to a user's presence events, use the subscribeToUsersPresence method. You need to pass an array of user IDs you want to track. The callback function will provide the status of these users.

Once subscribed, you can listen for online-user and offline-user events to react to changes in user status. These events are triggered whenever a user you are subscribed to changes their presence status.

const users = await session.subscribeToUsersPresence(['otherUserId'])

session
  .on('online-user', (onlineUser) => {
    // Handle subscribed user changing status to online
  })
  .on('offline-user', (offlineUser) => {
    // Handle subscribed user changing status to offline
  });
Comprehensive Feature Guide

Dive into the intricacies of the SDK with this detailed guide, exploring the essential components and their utilization within your application:

  • User: The User component is the cornerstone of user identity within the SDK, encapsulating vital attributes like unique identifiers and personal details, facilitating a personalized and secure user experience.
  • Session: The Session component acts as the critical bridge connecting your application to our backend, managing authentication and orchestrating the seamless flow of operations like chatroom interactions and real-time presence updates.
  • Chatroom: At the heart of user interaction, the Chatroom component serves as the dynamic environment for message exchanges, offering robust tools for managing conversations, participants, and message history.
  • Message: Each Message is a vital unit of communication within a chatroom, embodying the sender's intent, content, and metadata, while also reflecting its lifecycle stages from sending to reception and acknowledgment.

In the following sections, we will explore each component in greater detail, providing you with the knowledge to fully leverage the SDK's features.

User

The User component represents an application user and is a fundamental part of user management within the SDK. It encapsulates all the necessary information about a user, allowing for a robust and flexible way to handle user data within your application.

idstringA unique identifier for the user, ensuring each user is distinct within the application.
screenNamestringThe user's display name within the application, which may be different from their real name.
avatarUrlstringA URL pointing to the user's avatar image, providing a visual representation of the user.
emailstringThe user's email address, used for communication and identification purposes.
metadataMapA key-value store for additional information related to the user that can be used by the application.
onlinebooleanA boolean value indicating whether the user is currently online or offline.
lastSeennumberA timestamp indicating the last time the user was active or seen on the application (in nano precision).
Create user_constructor_
This method initializes a user instance and connects it to the ezajil backend, which, in turn, broadcasts an online presence event to all subscribers of the current user.
Parameters
userIdstringRequired

A unique identifier for the user, essential for differentiating each user within the application.

screenNamestringRequired

A display name for the user, used within the application interface.

avatarUrlstring

A link to the user's avatar image. This is optional and can be used to visually represent the user.

emailstring

The user's email address. While not mandatory, it is crucial for user identification and communication.

metadataMap

An optional key-value pair storage associated with the user, allowing for the storage of additional information pertinent to the user within the application context.

Returns
userUser

The newly created user instance.

const user = new User(userId, screenName, avatarUrl, email);
Session

The Session component is pivotal in linking your application with the ezajil backend, necessitating an active user instance and authentication credentials. To obtain these credentials and configure your session, please visit the ezajil dashboard.

Create session_constructor_
Connects the current user to the ezajil backend. This will trigger online presence event to all current user's subscribers.
Parameters
endpointstringRequired

ezajil provided endpoint, can be found on Dashboard

apiKeystringRequired

ezajil provided api key, can be found on Dashboard

userUserRequired

current user

sdkConfigObject

optional SDK global configuration settings, such as enabling or disabling logging

Returns
sessionSession

the newly created session instance

const currentUser = new User(userId, screenName, avatarUrl, email);
const sdkConfig = {
  enableLogging: true
};
const session = new Session('your-endpoint', 'your-apiKey', currentUser, sdkConfig);
Manage Session Lifecycle
Connect sessionconnect
Establishes a connection between the current user and ezajil backend, which in turn activates online presence notifications for the user's subscribers.
Parameters

No parameters.

session.connect();
Disconnect Sessiondisconnect
Disconnects the current user's connection with the ezajil backend, triggering an offline presence notification for the user's subscribers.
Parameters

No parameters.

session.disconnect();
Interact with Chatrooms
Create a Private 1-to-1 ChatroomcreateSingleChatroom
Creates a private chatroom between the current user and another specified user.
Parameters
namestringRequired

The name associated with the chatroom, useful for display purposes.

participantIdstring[]Required

The unique identifier of the other user in this private chatroom.

metadataMap

A key-value store for holding extra information pertinent to the chatroom.

Output
errorAPIError | null

Details of any error that occurred during chatroom creation.

chatroomChatroom | null

The newly created chatroom object.

session.createSingleChatroom(name, participantId, metadata)
  .then(chatroom => {
    // Handle created chatroom
  })
  .catch(error => {
    // Handle the error, an APIError type with status, message, and details attributes
  });
Create a Group ChatroomcreateGroupChatroom
Creates a new group chatroom with specified participants.
Parameters
namestringRequired

The name associated with the chatroom, intended for display purposes.

participantIdsstring[]Required

The unique identifiers of the users included in the chatroom.

metadataMap

A key-value pair storage for additional information pertinent to the chatroom.

Output
errorAPIError | null

Details of any error encountered during the creation of the chatroom.

chatroomChatroom | null

The newly established group chatroom object.

session.createGroupChatroom(name, participantIds, metadata)
  .then(chatroom => {
    // Handle created chatroom
  })
  .catch(error => {
    // Handle the error, an APIError type with status, message, and details attributes
  });
Get Chatroom by IDgetChatroomById
Retrieves the details of a specific chatroom using its unique identifier.
Parameters
chatroomIdstringRequired

The unique identifier of the chatroom to be fetched.

Output
errorAPIError | null

Details of any error that occurred during the retrieval process.

chatroomChatroom | null

The retrieved chatroom object.

session.getChatroomById(chatroomId)
  .then(chatroom => {
    // Handle chatroom
  })
  .catch(error => {
    // Handle the error, an APIError type with status, message, and details attributes
  });
Get User's ChatroomsgetChatroomsOfUser
Retrieves a list of chatrooms that the current user is a part of.
Parameters

No parameters.

Output
errorAPIError | null

Details of any error encountered during the fetch process.

chatroomsChatroom[] | null

An array of chatroom objects associated with the user.

session.getChatroomsOfUser()
  .then(chatrooms => {
    // Handle user's chatrooms
  })
  .catch(error => {
    // Handle the error, an APIError type with status, message, and details attributes
  });
Interact with Users
Get Chatroom UsersgetChatroomUsers
Retrieves a list of users participating in a specified chatroom.
Parameters
chatroomIdstringRequired

The unique identifier of the chatroom whose users are being requested.

Output
errorAPIError | null

Details of any error encountered during the user fetch process.

usersUser[] | null

An array of User objects representing the participants of the chatroom.

session.getChatroomUsers(chatroomId)
  .then(users => {
    // Handle chatroom users
  })
  .catch(error => {
    // Handle the error, an APIError type with status, message, and details attributes
  });
Retrieve UsersgetUsers
Retrieves a collection of users based on their unique identifiers.
Parameters
userIdsstring[]Required

The array of user identifiers for the users to be fetched.

Output
errorAPIError | null

Any error that occurred during the fetch operation.

usersUser[] | null

An array of user objects corresponding to the fetched user IDs.

session.getUsers(userIds)
  .then(users => {
    // Handle users
  })
  .catch(error => {
    // Handle the error, an APIError type with status, message, and details attributes
  });
Manage Presence Subscriptions
Subscribe to Users' Presence EventssubscribeToUsersPresence
Enables the current user to monitor the online status of specified users through presence events.
Parameters
userIdsstring[]Required

The identifiers of the users whose presence events we wish to subscribe to.

Output
errorAPIError | null

Details of any errors encountered during the subscription process.

usersUser[] | null

A list of users with their current presence status.

session.subscribeToUsersPresence(userIds)
  .then(users => {
    // Handle users
  })
  .catch(error => {
    // Handle the error, an APIError type with status, message, and details attributes
  });
Unsubscribe from Users' Presence EventsunsubscribeFromUsersPresence
Ceases the current user's subscription to the presence updates of selected users.
Parameters
userIdsstring[]Required

The identifiers of the users from whom to unsubscribe presence updates.

Output
errorAPIError | null

Details of any errors that occurred during the unsubscription process.

session.unsubscribeFromUsersPresence(userIds)
  .then(() => {
    // Successful unsubscribe
  })
  .catch(error => {
    // Handle the error, an APIError type with status, message, and details attributes
  });
Unsubscribe from All Users' Presence EventsunsubscribeFromAllUsersPresence
This operation disconnects the current user from receiving presence updates for all users they previously subscribed to.
Parameters

No parameters.

Output
errorAPIError | null

Details of any errors encountered during the unsubscription process.

session.unsubscribeFromAllUsersPresence()
  .then(() => {
    // Successful unsubscribe
  })
  .catch(error => {
    // Handle the error, an APIError type with status, message, and details attributes
  });
Manage Message Receipts
Fire User TypingfireUserTyping
Initiates a user-typing event in the specified chatroom, signaling to other participants that the current user is typing a message. Currently, this feature is available exclusively for Private chatrooms.
Parameters
chatroomIdstringRequired

The identifier of the chatroom where the typing event is being signaled.

session.fireUserTyping(chatroomId);
Mark Messages as DeliveredmarkMessageAsDelivered
Designates messages within a specified chatroom as delivered, triggering a messages-delivered event for recipients to acknowledge. Currently, this functionality is exclusive to Private chatrooms.
Parameters
chatroomIdstringRequired

The identifier of the chatroom where messages are marked as delivered.

latestMessageDeliveredTimestampnumberRequired

Timestamp indicating the sending date of the most recent message confirmed as delivered, in nano precision.

session.markMessageAsDelivered(chatroomId, latestMessageDeliveredTimestamp);
Mark Messages as ReadmarkMessagesAsRead
Designates messages within a specified chatroom as read, triggering a messages-read event for other participants. Currently, this feature is available exclusively for Private chatrooms.
Parameters
chatroomIdstringRequired

The identifier of the chatroom where messages are marked as read.

latestMessageReadTimestampnumberRequired

Timestamp for the sending date of the most recent message that was read, in nano precision.

session.markMessageAsRead(chatroomId, latestMessageReadTimestamp);
Handle Session Events

In our SDK, events play a crucial role in enabling real-time responsiveness and interactivity within your application. By listening to various events, your application can react dynamically to changes and activities occurring in the system. Events provide a powerful way to hook into the core functionality of the SDK, allowing you to execute custom logic when specific actions or changes occur. Whether it's detecting a user's presence, receiving messages, or handling errors, events ensure your application stays synchronized with the state of the chat environment.

Below, we detail the available events and their respective payloads, offering insights into the data you can leverage to enhance user experience and application performance.

session
 .on('connected', () => {
  // Handle session connected event
 })
 .on('disconnected', (code, reason, isClientError) => {
  // Handle session disconnected event
 })
 .on('online-user', (onlineUser) => {
  // Handle online-user event
 })
 .on('offline-user', (offlineUser) => {
  // Handle offline-user event
 })
...
Chatroom

The Chatroom component is an integral part of the messaging framework, encapsulating the environment where users engage in conversations.

It is designed to accommodate both one-on-one and group interactions, providing a versatile structure to support various communication scenarios.

chatroomIdstringA unique identifier for the chatroom.
namestringThe name or title of the chatroom.
latestMessagestringThe most recent message sent in the chatroom.
creationDatestringThe timestamp indicating when the chatroom was created.
creatorIdstringThe unique identifier of the user who created the chatroom.
singlebooleanIndicates whether the chatroom is a private, one-on-one chat.
participantIdsstring[]An array of user IDs representing the participants of the chatroom.
metadataMapA key-value pair object for storing additional information related to the chatroom that can be used by the application.
Retrieve MessagesgetMessages
Retrieves a set of messages from a chatroom, offering paginated access to the chat history. Messages are presented in reverse chronological order.
Parameters
fromstringRequired

The starting point for pagination.

limitstringRequired

The maximum number of messages to fetch in this request.

Output
errorAPIError | null

Any error encountered during the retrieval process.

messagesMessage[] | null

An array of message objects fetched from the chatroom.

chatroom.getMessages(from, limit)
  .then(messages => {
    // Handle messages
  })
  .catch(error => {
    // Handle the error, an APIError type with status, message, and details attributes
  });
Retrieve Chatroom UsersgetUsers
Retrieves a list of users participating in a specific chatroom.
Parameters

No parameters.

Returns
errorAPIError | null

Details of any errors that occurred during the user retrieval process.

usersUser[] | null

An array of user objects representing the participants of the chatroom.

chatroom.getUsers()
  .then(users => {
    // Handle chatroom users
  })
  .catch(error => {
    // Handle the error, an APIError type with status, message, and details attributes
  });
Send Text MessagesendChatMessage
Sends a text message from the current user within a specified chatroom.
Parameters
messagestringRequired

The text content of the message to be sent.

Returns
messageMessage | null

The message object that was sent, including its details and status.

chatroom.sendChatMessage('Hello World!');
Upload AttachmentuploadFile
Enables the current user to upload an attachment file within a chatroom.
Parameters
fileFileRequired

The file to be uploaded as an attachment.

Output
errorAPIError | null

Details of any errors that occurred during the file upload process.

messageMessage | null

The message object associated with the uploaded file, detailing the upload status and file information.

const file = document.getElementById('attachmentInput').files[0];
chatroom.uploadFile(file, (message, error) => {
  .then(message => {
    // Process the uploaded message
    // This message will contain the link of the uploaded attachment
  })
  .catch(error => {
    // Handle the error, an APIError type with status, message, and details attributes
  });
Fire user typingfireUserTyping
Initiates a user-typing event in the specified chatroom, signaling to other participants that the current user is typing a message. Currently, this feature is available exclusively for Private chatrooms.
Parameters

No parameters.

chatroom.fireUserTyping();
Mark messages as deliveredmarkMessageAsDelivered
Designates messages within a specified chatroom as delivered, triggering a messages-delivered event for recipients to acknowledge. Currently, this functionality is exclusive to Private chatrooms.
Parameters
latestMessageDeliveredTimestampnumberRequired

Timestamp indicating the sending date of the most recent message confirmed as delivered, in nano precision.

chatroom.markMessagesAsDelivered(latestMessageDeliveredTimestamp);
Mark messages as readmarkMessagesAsRead
Designates messages within a specified chatroom as read, triggering a messages-read event for other participants. Currently, this feature is available exclusively for Private chatrooms.
Parameters
latestMessageReadTimestampnumberRequired

Timestamp for the sending date of the most recent message that was read, in nano precision.

chatroom.markMessagesAsRead(latestMessageReadTimestamp);
Handle Chatroom Events

Chatroom events provide a granular level of interaction within specific chatroom contexts, allowing developers to respond to various actions and updates that occur within those environments. While some events, such as chat-message, user-typing, message-sent, messages-delivered, and messages-read, are also available at the session level, there are instances where monitoring these events at the chatroom level is necessary for more targeted functionality and logic.

Below, we detail the available events and their respective payloads, offering insights into the data you can leverage.

Message

The Message component is a core entity in the messaging system, encapsulating all the necessary information about a single message within a chatroom.

chatroomIdstringThe identifier of the chatroom to which the message belongs, linking the message to its conversational context.
messageIdstringA unique identifier for the message, ensuring each message can be distinctly referenced and managed.
authorstringThe identifier of the user who authored the message, providing accountability and context within the chat.
screenNamestringThe display name of the message author as it should appear within the chat interface.
contentstringThe textual content of the message, which may include text, emojis, or other forms of data meant for display.
mediaUrls{ [key: string]: string }A dictionary of media URLs attached to the message, allowing for the inclusion of images, videos, or other multimedia content.
previewbooleanA flag indicating whether the message includes a preview of linked content, enhancing user interaction and engagement.
sendingDatenumberA timestamp representing when the message was sent in nano precision, used for ordering messages chronologically in the chat view.
status'NOT_SENT' | 'SENT' | 'DELIVERED' | 'READ'The current status of the message, indicating its delivery and read state, which helps in providing feedback to the sender.
systemMessagebooleanA boolean indicating whether the message is a system-generated notification or a user-generated message, differentiating between automated and direct communication.