@paanj/chat-client
v1.0.5
Published
Chat client features for Paanj platform - real-time messaging and conversations
Maintainers
Readme
@paanj/chat-client
Build powerful real-time chat applications with ease.
Overview
The @paanj/chat-client SDK empowers developers to integrate robust, real-time messaging capabilities into their applications. Whether you're building a social platform, a customer support tool, or an internal collaboration app, our SDK handles the heavy lifting of real-time communication.
Key Features
- 💬 Real-time Messaging: Instant message delivery with low latency.
- 👥 Group Conversations: Create and manage dynamic group chats and direct messages.
- 🔔 Live Events: Subscribe to real-time updates for new messages and conversation changes.
- 🌐 Cross-Platform: Fully isomorphic design working seamlessly in Node.js and modern browsers.
- 🔒 Secure: Built with security in mind, integrating with
@paanj/clientfor robust authentication.
Installation
npm install @paanj/client @paanj/chat-clientQuick Start
Get up and running in minutes.
import { PaanjClient } from '@paanj/client';
import { ChatClient } from '@paanj/chat-client';
// 1. Initialize the core client
const client = new PaanjClient({ apiKey: 'YOUR_PUBLIC_API_KEY' });
// 2. Authenticate your user (required before using chat)
const session = await client.authenticateAnonymous({
name: 'Alice',
metadata: { email: '[email protected]' }
});
console.log('User ID:', session.userId);
// 3. Connect to real-time server
await client.connect();
// 4. Initialize the Chat SDK
const chat = new ChatClient(client);
// 5. Create a conversation
const conversation = await chat.conversations.create({
name: 'Team Project',
participantIds: [session.userId, 'user_456']
});
// 6. Listen for incoming messages globally
chat.conversations.onMessage((message) => {
console.log(`[${message.senderId}]: ${message.content}`);
});
// 7. Listen for token refresh events
chat.users.onTokenRefresh(({ userId, accessToken, refreshToken }) => {
console.log('Token refreshed for user:', userId);
});
// 8. Send a message
await chat.conversations(conversation.id).send('Hello, team! 👋');API Reference
Initialization
new ChatClient(client)
Creates a new instance of the Chat SDK.
client: An authenticatedPaanjClientinstance (you must callauthenticateAnonymous()orauthenticateWithToken()first).
Authentication
Before using chat features, you must authenticate:
// Option A: Anonymous authentication (creates a new user)
const session = await client.authenticateAnonymous({
name: 'John Doe',
metadata: { email: '[email protected]' }
});
// Option B: Existing session (reuse previous access token)
await client.authenticateWithToken(
'ACCESS_TOKEN',
'USER_ID', // Optional, can be extracted from token
'REFRESH_TOKEN' // Required for token refresh functionality
);
// Get user ID after authentication
const userId = client.getUserId();
console.log('Session User ID:', userId);Conversations
Manage chat rooms and direct messages.
chat.conversations.create(data)
Creates a new conversation.
data: Object containingname(optional) andparticipantIds.- Returns:
Promise<Conversation>
chat.conversations.list(filters?)
Retrieves a list of conversations the current user is part of.
- Returns:
Promise<Conversation[]>
chat.conversations.get(conversationId)
Retrieves details for a specific conversation.
- Returns:
Promise<Conversation>
Conversation Context
Interact with a specific conversation using the fluent API: chat.conversations(conversationId)
.send(content, metadata?)
Sends a message to the conversation.
content: The text content of the message.metadata: Optional JSON object for custom data (currently not processed by the server).- Returns:
Promise<void>
const ctx = chat.conversations(conversation.id);
await ctx.send('Hello!');.messages().list(filters?)
Retrieves message history with fluent API chaining.
.limit(n): Limit number of messages..page(n): Specific page number..offset(n): Specific offset.- Returns:
Promise<Message[]>
const history = await chat.conversations(id)
.messages()
.list()
.limit(20)
.page(1);.participants().list()
List all participants in the conversation.
- Returns:
Promise<Participant[]>
const participants = await chat.conversations(id)
.participants()
.list();.participants().add(userId, role?)
Add a user to the conversation (Admin only).
userId: ID of the user to add.role: 'admin' or 'member' (default: 'member').- Returns:
Promise<void>
await chat.conversations(id)
.participants()
.add('user_789', 'member');.leave()
Removes the current user from the conversation.
- Returns:
Promise<void>
await chat.conversations(conversation.id).leave();.get()
Retrieves details for this conversation.
- Returns:
Promise<Conversation>
const details = await chat.conversations(id).get();.onUpdate(callback)
Listen to updates for this conversation.
callback: Function called when conversation is updated.- Returns:
Unsubscribefunction.
chat.conversations(id).onUpdate((update) => {
console.log('Updated:', update);
});Messages
Listen to messages in specific conversations.
chat.conversations.onMessage(callback)
Subscribes to real-time messages globally (for all conversations).
callback: Function called when a new message is created.- Returns:
Unsubscribefunction (call to stop listening).
const unsubscribe = chat.conversations.onMessage((message) => {
console.log(`New message from ${message.senderId}: ${message.content}`);
});
// Later, unsubscribe from messages
unsubscribe();Users
Manage user interactions including token refresh events and blocking.
chat.users.onTokenRefresh(callback)
Subscribes to token refresh events.
callback: Function called when the user's token is refreshed. Receives object withuserId,accessToken, andrefreshToken.- Returns:
Unsubscribefunction.
const unsubscribe = chat.users.onTokenRefresh(({ userId, accessToken, refreshToken }) => {
console.log(`Token refreshed for user ${userId}`);
// Handle token update (e.g., persist to secure storage)
});
// Later, unsubscribe from token updates
unsubscribe();chat.users.getBlocked()
Retrieves the list of blocked user IDs for the current user.
- Returns:
Promise<string[]>
const blockedIds = await chat.users.getBlocked();
console.log('Blocked users:', blockedIds);chat.users(userId)
Access user context for a specific user.
- Returns:
UserContext
const userCtx = chat.users('user_123');
// Listen for token refresh for this user
userCtx.onTokenRefresh(({ userId, accessToken, refreshToken }) => {
console.log(`Token refreshed for ${userId}`);
});
// Block/unblock this user
await userCtx.block();
await userCtx.unblock();Global Events (Deprecated)
The chat.onMessage() method has been removed. Use chat.conversations.onMessage(callback) instead to listen for messages globally.
Support
- 📖 Documentation: docs.paanj.com
- 🐛 Issues: GitHub Issues
- 📧 Contact: [email protected]
Made with ❤️ by the Paanj team
