sse typing
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
export * from "./fastify.js";
|
||||
export * from "./homeassistant.js";
|
||||
export * from "./logger.js";
|
||||
export * from "./sse.js";
|
||||
export * from "./tidal.js";
|
||||
export * from "./timehelper.js";
|
||||
|
||||
|
||||
43
src/sse.ts
Normal file
43
src/sse.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user