| import type { Response } from "express"; |
|
|
| const connections = new Map<string, Set<Response>>(); |
|
|
| export function addConnection(userId: string, res: Response): void { |
| if (!connections.has(userId)) connections.set(userId, new Set()); |
| connections.get(userId)!.add(res); |
| } |
|
|
| export function removeConnection(userId: string, res: Response): void { |
| const set = connections.get(userId); |
| if (!set) return; |
| set.delete(res); |
| if (set.size === 0) connections.delete(userId); |
| } |
|
|
| export function sendEvent(userId: string, event: string, data: unknown = {}): void { |
| const set = connections.get(userId); |
| if (!set) return; |
| const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; |
| for (const res of set) { |
| try { res.write(payload); } catch { } |
| } |
| } |
|
|
| export function broadcastToUsers(userIds: string[], event: string, data: unknown = {}): number { |
| let sent = 0; |
| for (const id of userIds) { |
| const set = connections.get(id); |
| if (!set) continue; |
| const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; |
| for (const res of set) { |
| try { res.write(payload); sent++; } catch { } |
| } |
| } |
| return sent; |
| } |
|
|