From 2cb4a649bd92a7705efc6edce7f4178d59cbe96f Mon Sep 17 00:00:00 2001 From: pradeepkumar Date: Tue, 17 Mar 2026 18:02:53 +0530 Subject: [PATCH] feat: Improve message broadcasting to exclude sender, add error handling for direct delivery, and enhance `sendToUser` logging. --- src/messages/messages.gateway.ts | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/messages/messages.gateway.ts b/src/messages/messages.gateway.ts index d2086cb..82ef9b9 100644 --- a/src/messages/messages.gateway.ts +++ b/src/messages/messages.gateway.ts @@ -175,19 +175,23 @@ export class MessagesGateway implements OnGatewayConnection, OnGatewayDisconnect data.message, ); - // Broadcast to all clients in the conversation room - this.server + // Broadcast to other clients in the conversation room (exclude sender) + client .to(`conversation:${data.conversationId}`) .emit('new_message', message); // Also send directly to the other participant's socket(s) // so they receive the message even if they haven't joined this room - const participants = await this.messagesService.getConversationParticipants(data.conversationId); - if (participants) { - const otherUserId = client.userId === participants.userId - ? participants.agentUserId - : participants.userId; - this.sendToUser(otherUserId, 'new_message', message); + try { + const participants = await this.messagesService.getConversationParticipants(data.conversationId); + if (participants) { + const otherUserId = client.userId === participants.userId + ? participants.agentUserId + : participants.userId; + this.sendToUser(otherUserId, 'new_message', message); + } + } catch (participantError) { + this.logger.warn(`Failed to get participants for direct delivery in ${data.conversationId}: ${participantError.message}`); } return { success: true, message }; @@ -381,10 +385,13 @@ export class MessagesGateway implements OnGatewayConnection, OnGatewayDisconnect */ sendToUser(userId: string, event: string, data: any) { const sockets = this.userSocketMap.get(userId); - if (sockets) { + if (sockets && sockets.size > 0) { sockets.forEach((socketId) => { this.server.to(socketId).emit(event, data); }); + this.logger.debug(`Sent ${event} to user ${userId} via ${sockets.size} socket(s)`); + } else { + this.logger.debug(`User ${userId} has no active sockets for ${event} - message saved in DB`); } }