MCPcopy Create free account
hub / github.com/code100x/chess / SocketManager

Class SocketManager

apps/ws/src/SocketManager.ts:21–79  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

19}
20
21class SocketManager {
22 private static instance: SocketManager;
23 private interestedSockets: Map<string, User[]>;
24 private userRoomMappping: Map<string, string>;
25
26 private constructor() {
27 this.interestedSockets = new Map<string, User[]>();
28 this.userRoomMappping = new Map<string, string>();
29 }
30
31 static getInstance() {
32 if (SocketManager.instance) {
33 return SocketManager.instance;
34 }
35
36 SocketManager.instance = new SocketManager();
37 return SocketManager.instance;
38 }
39
40 addUser(user: User, roomId: string) {
41 this.interestedSockets.set(roomId, [
42 ...(this.interestedSockets.get(roomId) || []),
43 user,
44 ]);
45 this.userRoomMappping.set(user.userId, roomId);
46 }
47
48 broadcast(roomId: string, message: string) {
49 const users = this.interestedSockets.get(roomId);
50 if (!users) {
51 console.error('No users in room?');
52 return;
53 }
54
55 users.forEach((user) => {
56 user.socket.send(message);
57 });
58 }
59
60 removeUser(user: User) {
61 const roomId = this.userRoomMappping.get(user.userId);
62 if (!roomId) {
63 console.error('User was not interested in any room?');
64 return;
65 }
66 const room = this.interestedSockets.get(roomId) || []
67 const remainingUsers = room.filter(u =>
68 u.userId !== user.userId
69 )
70 this.interestedSockets.set(
71 roomId,
72 remainingUsers
73 );
74 if (this.interestedSockets.get(roomId)?.length === 0) {
75 this.interestedSockets.delete(roomId);
76 }
77 this.userRoomMappping.delete(user.userId);
78 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected