Javascript (frontend)
Introduction
This library exposes the api used by the framework-specific modules. If you see the framework you are using listed as an option, it is recommended to use that library instead.
The ChatRoomConnection
module provides functionalities to connect to a chat room via WebSocket and fetch messages from the chat room using HTTP requests. This documentation serves as a guide for utilizing the ChatRoomConnection
module effectively.
Basics
Installation
This module is designed to be used in a Node.js environment. To use it, make sure you have Node.js installed, then install the module using npm:
npm install @ezchat/frontend
Importing
To use the ChatRoomConnection
module in your project, import it as follows:
import { ChatRoomConnection } from '@ezchat/frontend';
Connecting to a Chat Room WebSocket
To establish a WebSocket connection to a chat room, create an instance of ChatRoomConnection
and call the connectWebsocket
method:
const connection = new ChatRoomConnection({
roomId: 123,
authToken: 'yourAuthToken',
});
const { sendMessage, disconnect } = connection.connectWebsocket({
onOpen: () => console.log('WebSocket connection opened'),
onClose: () => console.log('WebSocket connection closed'),
onError: (error) => console.error('WebSocket connection error:', error),
onMessage: (message) => console.log('Received message:', message),
});
// Send a message
sendMessage('Hello, world!');
// Disconnect from the WebSocket
disconnect();
Fetching Messages
To fetch messages from the chat room via HTTP request, use the fetchMessages
method:
try {
const messages = await connection.fetchMessages();
console.log('Fetched messages:', messages);
} catch (error) {
console.error('Error fetching messages:', error);
}
Example
import { ChatRoomConnection } from 'chat-room-connection';
const connection = new ChatRoomConnection({
roomId: 123,
authToken: 'yourAuthToken',
});
const { sendMessage, disconnect } = connection.connectWebsocket({
onOpen: () => console.log('WebSocket connection opened'),
onClose: () => console.log('WebSocket connection closed'),
onError: (error) => console.error('WebSocket connection error:', error),
onMessage: (message) => console.log('Received message:', message),
});
// Send a message
sendMessage('Hello, world!');
// Fetch messages
try {
const messages = await connection.fetchMessages();
console.log('Fetched messages:', messages);
} catch (error) {
console.error('Error fetching messages:', error);
}
// Disconnect from the WebSocket
disconnect();
API Reference
connectToChatRoomWebsocket(roomId: number, authToken?: string): WebSocket
Establishes a WebSocket connection to the specified chat room.
roomId
: The ID of the chat room to connect to.authToken
: Optional. An authentication token for the user.
Returns a WebSocket instance.
ChatRoomConnection
A class representing a connection to a chat room.
Constructor
constructor(props: IChatRoomConnectionProps)
props
: An object containing the following properties:roomId
: The ID of the chat room to connect to.authToken
: Optional. An authentication token for the user.messageCallback
: Optional. A callback function to handle incoming messages.authFunction
: Optional. A function that returns a Promise resolving to an authentication token.
Methods
async refreshToken(): void
Refreshes the authentication token asynchronously.
async fetchMessages(cursor?: string, size?: number): Promise<CursorPaginatedMessages>
Fetches messages from the chat room via HTTP request.
cursor
: Optional. A cursor indicating the position from which to fetch messages.size
: Optional. The number of messages to fetch.
Returns a Promise resolving to a CursorPaginatedMessages
object.
connectWebsocket(socketCallbacks?: IConnectWebsocketCallbacks): { sendMessage: Function, disconnect: Function }
Connects to the chat room via WebSocket.
socketCallbacks
: Optional. An object containing callback functions for various WebSocket events.
Returns an object with sendMessage
and disconnect
functions.
Interface IChatRoomConnectionProps
interface IChatRoomConnectionProps {
roomId: number;
authToken?: string;
messageCallback?: (message: ChatRoomMessagePayload) => void;
authFunction?: () => Promise<string>;
}
roomId
: The ID of the chat room to connect to.authToken
: Optional. An authentication token for the user.messageCallback
: Optional. A callback function to handle incoming messages.authFunction
: Optional. A function that returns a Promise resolving to an authentication token.
Interface IConnectWebsocketCallbacks
interface IConnectWebsocketCallbacks {
onOpen?: () => void;
onError?: (err: WebSocket.ErrorEvent) => void;
onClose?: () => void;
onMessage?: (message: ChatRoomWebsocketMessage) => void;
}
onOpen
: Optional. Callback function called when the WebSocket connection is opened.onError
: Optional. Callback function called when an error occurs in the WebSocket connection.onClose
: Optional. Callback function called when the WebSocket connection is closed.onMessage
: Optional. Callback function called when a message is received via WebSocket.