Managing Chat Members
This guide explains how to add and remove members from chat channels using the Agglestone Messaging Service.
Overview
Chat members are the users who can participate in a chat conversation. Only members can:
- Send messages to the chat
- View messages in the chat
- See other members of the chat
- Add new members to the chat
When you create a chat, you specify the initial members. After creation, you can add additional members or remove existing members as needed.
Viewing Chat Members
Before adding or removing members, you may want to see who is currently in a chat.
Retrieving Chat Members
Endpoint: GET /tenant/{tenantId}/v1/Chat/{chatId}/members
Query Parameters:
pageNumber(optional, default: 1): The page number to retrievepageSize(optional, default: 10, max: 50): The number of members per page
Response:
{
"data": [
"user-id-1",
"user-id-2",
"user-id-3"
],
"pageNumber": 1,
"pageSize": 10,
"totalCount": 3,
"totalPages": 1,
"hasPreviousPage": false,
"hasNextPage": false
}
The response includes an array of user IDs for all members of the chat, along with pagination information.
Example: Viewing Chat Members
async function getChatMembers(chatId: string, pageNumber: number = 1, pageSize: number = 50) {
const params = new URLSearchParams({
pageNumber: pageNumber.toString(),
pageSize: pageSize.toString()
});
const response = await fetch(
`${apiBaseUrl}/tenant/${tenantId}/v1/Chat/${chatId}/members?${params}`,
{
headers: {
'Authorization': `Bearer ${accessToken}`
}
}
);
if (!response.ok) {
throw new Error(`Failed to fetch chat members: ${response.statusText}`);
}
return await response.json();
}
// Get all members of a chat
const members = await getChatMembers(chatId);
console.log('Chat members:', members.data);
Adding Members to a Chat
You can add new users to an existing chat. Only existing chat members can add new members, ensuring that conversations remain private and controlled.
Adding a Member
Endpoint: POST /tenant/{tenantId}/v1/Chat/{chatId}/members
Request Body:
{
"userId": "user-id-to-add"
}
userId(required): The user ID of the person to add to the chat
Response:
{
"message": "Member added to chat successfully"
}
Example: Adding a Member
async function addMemberToChat(chatId: string, userId: string) {
const response = await fetch(
`${apiBaseUrl}/tenant/${tenantId}/v1/Chat/${chatId}/members`,
{
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
userId: userId
})
}
);
if (!response.ok) {
throw new Error(`Failed to add member: ${response.statusText}`);
}
return await response.json();
}
// Add a user to a chat
await addMemberToChat(chatId, 'user-id-to-add');
What Happens When a Member is Added
When you add a member to a chat:
- The user is immediately added as a member
- They can now send messages and view the conversation
- They will receive real-time WebSocket notifications for new messages
- They can see all existing messages in the chat (conversation history is accessible to all members)
Important Notes:
- You must be a member of the chat to add other members
- The user being added must exist in your tenant
- You cannot add a user who is already a member (the operation will succeed but have no effect)
Removing Members from a Chat
You can remove members from a chat. Users can remove themselves, or other chat members can remove them.
Removing a Member
Endpoint: DELETE /tenant/{tenantId}/v1/Chat/{chatId}/members/{userId}
Response:
{
"message": "Member removed from chat successfully"
}
Example: Removing a Member
async function removeMemberFromChat(chatId: string, userId: string) {
const response = await fetch(
`${apiBaseUrl}/tenant/${tenantId}/v1/Chat/${chatId}/members/${userId}`,
{
method: 'DELETE',
headers: {
'Authorization': `Bearer ${accessToken}`
}
}
);
if (!response.ok) {
throw new Error(`Failed to remove member: ${response.statusText}`);
}
return await response.json();
}
// Remove a user from a chat (or remove yourself)
await removeMemberFromChat(chatId, 'user-id-to-remove');
// Users can remove themselves
await removeMemberFromChat(chatId, currentUserId);
What Happens When a Member is Removed
When you remove a member from a chat:
- The user is immediately removed as a member
- They can no longer send messages to the chat
- They can no longer view messages in the chat
- They will stop receiving real-time WebSocket notifications for this chat
- They cannot re-add themselves (another member must add them back)
Important Notes:
- Users can always remove themselves from a chat
- To remove another user, you must be a member of the chat
- Removing a member does not delete the chat or any messages
- The removed user loses access to the chat but historical messages remain in the database
Use Cases
Adding Team Members to a Project Chat
// Add multiple team members to a project discussion chat
const teamMemberIds = ['user-id-1', 'user-id-2', 'user-id-3'];
for (const memberId of teamMemberIds) {
await addMemberToChat(projectChatId, memberId);
}
Allowing Users to Leave a Chat
// User clicks "Leave Chat" button
async function leaveChat(chatId: string) {
await removeMemberFromChat(chatId, currentUserId);
// Update UI to remove chat from user's chat list
}
Moderating Chat Membership
// Remove a user who is no longer part of a project
async function removeUserFromProjectChat(chatId: string, userId: string) {
// Verify current user has permission (e.g., is project admin)
if (await isProjectAdmin(currentUserId)) {
await removeMemberFromChat(chatId, userId);
} else {
throw new Error('Only project admins can remove members');
}
}
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 (required to add/remove members), or the tenant ID doesn’t match your authentication.
- 404 Not Found: The chat doesn’t exist, the user doesn’t exist, or the user is not a member of the chat (when removing).
- 400 Bad Request: Invalid request body (e.g., missing userId when adding a member).
Always check the response status and handle errors appropriately in your application.
—
Ready to get started? Check out the Quick Start Guide.