feat: stabilize social backend contracts

هذا الالتزام موجود في:
boutmoun123
2026-05-31 16:13:23 +03:00
الأصل ad6da6754d
التزام 49e132909e
40 ملفات معدلة مع 12037 إضافات و9562 حذوفات

عرض الملف

@@ -14,6 +14,7 @@ import { Server, Socket } from 'socket.io';
import { ChatRealtimeService } from './chat-realtime.service';
import { ChatService } from './chat.service';
import { SendMessageDto } from './dto/send-message.dto';
import { UsersService } from '../users/users.service';
type SocketWithUser = Socket & { data: { userId?: string } };
@@ -21,12 +22,14 @@ type SocketWithUser = Socket & { data: { userId?: string } };
export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect {
@WebSocketServer()
server!: Server;
private readonly connectionCountsByUser = new Map<string, number>();
constructor(
private readonly chatService: ChatService,
private readonly chatRealtimeService: ChatRealtimeService,
private readonly jwtService: JwtService,
private readonly configService: ConfigService,
private readonly usersService: UsersService,
) {}
afterInit(server: Server) {
@@ -49,6 +52,8 @@ export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
return;
}
client.data.userId = payload.sub;
this.incrementUserConnection(payload.sub);
await this.usersService.setPresence(payload.sub, true);
await client.join(this.userRoom(payload.sub));
this.server.to(this.userRoom(payload.sub)).emit('presence', { userId: payload.sub, online: true });
} catch {
@@ -59,7 +64,11 @@ export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
handleDisconnect(client: SocketWithUser) {
const userId = client.data.userId;
if (userId) {
this.server.to(this.userRoom(userId)).emit('presence', { userId, online: false });
const remainingConnections = this.decrementUserConnection(userId);
if (remainingConnections === 0) {
void this.usersService.setPresence(userId, false);
this.server.to(this.userRoom(userId)).emit('presence', { userId, online: false });
}
}
}
@@ -140,4 +149,18 @@ export class ChatGateway implements OnGatewayInit, OnGatewayConnection, OnGatewa
private conversationRoom(conversationId: string): string {
return `conversation:${conversationId}`;
}
private incrementUserConnection(userId: string): void {
this.connectionCountsByUser.set(userId, (this.connectionCountsByUser.get(userId) ?? 0) + 1);
}
private decrementUserConnection(userId: string): number {
const nextCount = Math.max(0, (this.connectionCountsByUser.get(userId) ?? 1) - 1);
if (nextCount === 0) {
this.connectionCountsByUser.delete(userId);
return 0;
}
this.connectionCountsByUser.set(userId, nextCount);
return nextCount;
}
}