Reassign a chat
Preserve chat history when assigning a booking or job to a new provider.
On a platform where customers book services from providers, or where workers are assigned to jobs, changing the assignment also changes who should have access to the chat. This guide shows how to remove the current assignee's access and add the new provider, preserving the full conversation history without any input from the customer.
We'll use a home-cleaning booking platform as an example. Customers chat with the cleaner assigned to their visit. If the customer has already sent messages explaining how to enter the property, the new cleaner needs to see those messages when the booking is reassigned.
Call reassignChat from the backend code that handles reassignment in your app, passing the booking's conversation ID and the two cleaners' TalkJS user IDs. The function removes the previous cleaner from the conversation, then adds the new cleaner.
The setParticipant function adds or removes a user and retries temporary failures. Its implementation is shown in the next section.
async function reassignChat(conversationId, oldUserId, newUserId) {
if (oldUserId === newUserId) {
return;
}
await setParticipant(conversationId, oldUserId, false);
await setParticipant(conversationId, newUserId, true);
}The new cleaner can read the customer's entry instructions and reply in the same chat. The previous cleaner loses access. The customer keeps the chat and doesn't need to resend anything.
If a request fails because of a connection problem, a timeout, a rate limit or a server error, the code tries again after one second, then two seconds, then four seconds. If it still fails, the error goes back to the code that called reassignChat. Other request errors, such as invalid credentials, don't get retried.
If the update fails after removing the previous cleaner, the customer keeps the conversation and its history. Your app can retry reassignChat with the same IDs to finish the update.
// Your app ID from the TalkJS Dashboard.
const appId = '<APP_ID>';
async function setParticipant(conversationId, userId, shouldBeParticipant) {
const url = `https://api.talkjs.com/v1/${appId}/conversations/${encodeURIComponent(conversationId)}/participants/${encodeURIComponent(userId)}`;
// How long to wait before retrying failed requests (doubles each time)
let delay = 1000;
for (let attempt = 0; attempt < 4; attempt++) {
// Reuse your existing Admin JWT generation code
// Example: https://talkjs.com/docs/REST_API/#authentication
const token = generateAdminJwt();
const response = await fetch(url, {
method: shouldBeParticipant ? 'PUT' : 'DELETE',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
}
}).then(async (response) => {
await response.text();
return response;
}).catch((error) => {
if (attempt === 3) {
throw error;
}
return null;
});
if (response) {
if (response.status === 200) {
return;
}
// When removing, 404 means the user is already not a participant.
if (!shouldBeParticipant && response.status === 404) {
return;
}
// A 404 while adding is an error. Only retry 429 or 5xx, up to four attempts.
if ((response.status !== 429 && response.status < 500) || attempt === 3) {
throw new Error(`TalkJS returned HTTP ${response.status}`);
}
}
await new Promise((resolve) => {
setTimeout(resolve, delay);
});
delay = delay * 2;
}
}