44 lines
862 B
TypeScript
44 lines
862 B
TypeScript
import { logInfo } from "./logger";
|
|
|
|
export interface SseClient {
|
|
id: number;
|
|
send: (data: SseEvent) => void;
|
|
}
|
|
|
|
export interface SseEvent {
|
|
type: string;
|
|
data?: unknown;
|
|
message?: string;
|
|
}
|
|
|
|
export class SseService {
|
|
private clients = new Set<SseClient>();
|
|
|
|
addClient(client: SseClient): void {
|
|
this.clients.add(client);
|
|
logInfo(
|
|
`SSE client connected: ${client.id}. Total clients: ${this.clients.size}`,
|
|
);
|
|
}
|
|
|
|
removeClient(clientId: number): void {
|
|
const client = [...this.clients].find((c) => c.id === clientId);
|
|
if (client) {
|
|
this.clients.delete(client);
|
|
logInfo(
|
|
`SSE client disconnected: ${clientId}. Total clients: ${this.clients.size}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
notifyClients(event: SseEvent): void {
|
|
this.clients.forEach((client) => {
|
|
client.send(event);
|
|
});
|
|
}
|
|
|
|
getClientCount(): number {
|
|
return this.clients.size;
|
|
}
|
|
}
|