Creating Chats and Sending Messages
This guide explains how to create new chat channels and send messages to them using the Agglestone Messaging Service.
Creating a Chat
Before you can send messages, you need to create a chat channel. A chat channel is a conversation space where multiple users can exchange messages in real-time.
Creating a New Chat
To create a new chat, send a POST request to the chat creation endpoint:
Endpoint: POST /tenant/{tenantId}/v1/Chat
Request Body:
{
"name": "Project Discussion",
"memberUserIds": ["user-id-1", "user-id-2", "user-id-3"]
}
name(optional): A friendly name for the chat channel. If not provided, the chat will be unnamed.memberUserIds(required): An array of user IDs that should be members of the chat. The authenticated user (the one making the request) is automatically added as a member, so you don’t need to include your own user ID in this array.
Response:
{
"id": "chat-id-123",
"name": "Project Discussion",
"createdAt": "2024-01-15T10:30:00Z",
"createdBy": "your-user-id",
"memberCount": 3
}
The response includes:
id: The unique chat ID that you’ll use for all subsequent operations on this chatname: The chat name (if provided)createdAt: When the chat was createdcreatedBy: The user ID of the person who created the chatmemberCount: The total number of members in the chat
Example: Creating a Chat
async function createChat(memberUserIds: string[], chatName?: string) {
const response = await fetch(
`${apiBaseUrl}/tenant/${tenantId}/v1/Chat`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: chatName,
memberUserIds: memberUserIds
})
}
);
if (!response.ok) {
throw new Error(`Failed to create chat: ${response.statusText}`);
}
const chat = await response.json();
console.log('Created chat:', chat);
return chat;
}
// Create a chat with two other users
const chat = await createChat(['user-id-2', 'user-id-3'], 'Team Chat');
Sending Messages
Once you have a chat ID, you can send messages to that chat. All members of the chat will receive real-time notifications through their WebSocket connections.
Sending a Message
To send a message to a chat, send a POST request to the message creation endpoint:
Endpoint: POST /tenant/{tenantId}/v1/Chat/{chatId}/messages
Request Body:
{
"message": "Hello, everyone!",
"clientId": "client-12345"
}
message(required): The message text contentclientId(optional): A unique identifier for the client sending the message (e.g., a browser tab ID). If provided, this client will not receive a WebSocket notification for the message it just sent, while other tabs/devices for the same user will still receive notifications. This prevents duplicate notifications in the sending client’s UI.
Response:
{
"id": "message-id-456",
"chatId": "chat-id-123",
"senderUserId": "your-user-id",
"message": "Hello, everyone!",
"createdAt": "2024-01-15T10:35:00Z"
}
The response includes:
id: The unique message IDchatId: The chat this message belongs tosenderUserId: The user ID of the person who sent the messagemessage: The message contentcreatedAt: When the message was created
Example: Sending a Message
async function sendMessage(chatId: string, messageText: string, clientId?: string) {
const response = await fetch(
`${apiBaseUrl}/tenant/${tenantId}/v1/Chat/${chatId}/messages`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
message: messageText,
clientId: clientId
})
}
);
if (!response.ok) {
throw new Error(`Failed to send message: ${response.statusText}`);
}
const message = await response.json();
console.log('Sent message:', message);
return message;
}
// Send a message to a chat
const message = await sendMessage(chat.id, 'Hello, everyone!', clientId);
Using clientId to Prevent Duplicate Message Events
When a user sends a message, they typically don’t want to receive a WebSocket notification for a message they just sent – they already know they sent it! However, if the same user has the chat open in multiple browser tabs or devices, those other tabs / devices should still receive notifications.
The clientId parameter solves this problem:
// Generate a unique client ID when your app starts (e.g., per browser tab)
const clientId = crypto.randomUUID();
// When sending a message, include the clientId
const message = await sendMessage(chatId, 'Hello!', clientId);
// This client (with this clientId) won't receive a WebSocket message event
// But other tabs / devices for the same user will still receive message events
Important Notes:
- You must be a member of the chat to send messages to it
- Messages are immediately persisted in the database
- All chat members receive real-time WebSocket message events (except the sending client if
clientIdis provided) - You should handle the WebSocket message event to update your UI when other users send messages
Error Handling
Common errors you may encounter:
- 401 Unauthorized: Your access token is missing, invalid, or expired. Refresh your token and retry.
- 403 Forbidden: You’re not a member of the chat, or the tenant ID doesn’t match your authentication.
- 404 Not Found: The chat ID doesn’t exist or you don’t have access to it.
- 400 Bad Request: The request body is invalid (e.g., missing required fields).
Always check the response status and handle errors appropriately in your application.
—
Ready to retrieve messages? Check out Retrieving Messages.