feat: Improve message broadcasting to exclude sender, add error handling for direct delivery, and enhance sendToUser logging.

This commit is contained in:
pradeepkumar
2026-03-17 18:02:53 +05:30
parent 960cdd8d48
commit 2cb4a649bd

View File

@@ -175,13 +175,14 @@ 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
try {
const participants = await this.messagesService.getConversationParticipants(data.conversationId);
if (participants) {
const otherUserId = client.userId === participants.userId
@@ -189,6 +190,9 @@ export class MessagesGateway implements OnGatewayConnection, OnGatewayDisconnect
: 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 };
} catch (error) {
@@ -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`);
}
}