File size: 1,185 Bytes
ccc21f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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 { /* tab closed */ }
  }
}

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 { /* ignore */ }
    }
  }
  return sent;
}