fb / artifacts /api-server /src /lib /sseManager.ts
sare26's picture
Upload 21 files
ccc21f3 verified
Raw
History Blame Contribute Delete
1.19 kB
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;
}