23 lines
526 B
TypeScript
23 lines
526 B
TypeScript
|
|
import { Response } from 'express';
|
||
|
|
|
||
|
|
const sseClients = new Set<Response>();
|
||
|
|
|
||
|
|
export function addSSEClient(res: Response): void {
|
||
|
|
sseClients.add(res);
|
||
|
|
}
|
||
|
|
|
||
|
|
export function removeSSEClient(res: Response): void {
|
||
|
|
sseClients.delete(res);
|
||
|
|
}
|
||
|
|
|
||
|
|
export function sseBroadcast(data: Record<string, any>): void {
|
||
|
|
const msg = `data: ${JSON.stringify(data)}\n\n`;
|
||
|
|
for (const c of sseClients) {
|
||
|
|
try { c.write(msg); } catch { sseClients.delete(c); }
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
export function getSSEClientCount(): number {
|
||
|
|
return sseClients.size;
|
||
|
|
}
|