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,
|
data.message,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Broadcast to all clients in the conversation room
|
// Broadcast to other clients in the conversation room (exclude sender)
|
||||||
this.server
|
client
|
||||||
.to(`conversation:${data.conversationId}`)
|
.to(`conversation:${data.conversationId}`)
|
||||||
.emit('new_message', message);
|
.emit('new_message', message);
|
||||||
|
|
||||||
// Also send directly to the other participant's socket(s)
|
// Also send directly to the other participant's socket(s)
|
||||||
// so they receive the message even if they haven't joined this room
|
// so they receive the message even if they haven't joined this room
|
||||||
|
try {
|
||||||
const participants = await this.messagesService.getConversationParticipants(data.conversationId);
|
const participants = await this.messagesService.getConversationParticipants(data.conversationId);
|
||||||
if (participants) {
|
if (participants) {
|
||||||
const otherUserId = client.userId === participants.userId
|
const otherUserId = client.userId === participants.userId
|
||||||
@@ -189,6 +190,9 @@ export class MessagesGateway implements OnGatewayConnection, OnGatewayDisconnect
|
|||||||
: participants.userId;
|
: participants.userId;
|
||||||
this.sendToUser(otherUserId, 'new_message', message);
|
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 };
|
return { success: true, message };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -381,10 +385,13 @@ export class MessagesGateway implements OnGatewayConnection, OnGatewayDisconnect
|
|||||||
*/
|
*/
|
||||||
sendToUser(userId: string, event: string, data: any) {
|
sendToUser(userId: string, event: string, data: any) {
|
||||||
const sockets = this.userSocketMap.get(userId);
|
const sockets = this.userSocketMap.get(userId);
|
||||||
if (sockets) {
|
if (sockets && sockets.size > 0) {
|
||||||
sockets.forEach((socketId) => {
|
sockets.forEach((socketId) => {
|
||||||
this.server.to(socketId).emit(event, data);
|
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