feat: Improve message broadcasting to exclude sender, add error handling for direct delivery, and enhance sendToUser logging.
This commit is contained in:
@@ -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`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user