make clients of sse service observable

This commit is contained in:
Darius
2026-02-05 22:05:35 +01:00
parent 921882054d
commit a6d837f953
7 changed files with 76 additions and 11 deletions

View File

@@ -1,8 +1,8 @@
import { API_HA_DeskPosition } from "./homeassistant";
import { TidalGetCurrent } from "./tidal";
import { type API_HA_DeskPosition } from "./homeassistant";
import { type TidalGetCurrent } from "./tidal";
export type FullInformation = {
ha_desk_position: API_HA_DeskPosition | null;
ha_temp: string | null;
tidal_current: TidalGetCurrent | null;
}
};

View File

@@ -4,22 +4,51 @@ import { logInfo } from "./logger.js";
export type SseClient = {
id: UUID;
send: (data: SseEvent) => void;
}
};
export type SseEvent = {
type: string;
data?: unknown;
message?: string;
}
};
export type SseClientChangeEvent = {
type: "add" | "remove";
clientId: string;
clientCount: number;
};
export type SseClientChangeCallback = (event: SseClientChangeEvent) => void;
export class SseService {
private clients: Map<string, SseClient> = new Map();
private clientChangeCallbacks: SseClientChangeCallback[] = [];
onClientChange(callback: SseClientChangeCallback): () => void {
this.clientChangeCallbacks.push(callback);
return () => {
this.clientChangeCallbacks = this.clientChangeCallbacks.filter(
(cb) => cb !== callback,
);
};
}
private emitClientChange(event: SseClientChangeEvent): void {
for (const callback of this.clientChangeCallbacks) {
callback(event);
}
}
addClient(client: SseClient): void {
this.clients.set(client.id, client);
logInfo(
`SSE client connected: ${client.id}. Total clients: ${this.clients.size}`,
);
this.emitClientChange({
type: "add",
clientId: client.id,
clientCount: this.clients.size,
});
}
removeClient(clientId: string): void {
@@ -27,12 +56,17 @@ export class SseService {
logInfo(
`SSE client disconnected: ${clientId}. Total clients: ${this.clients.size}`,
);
this.emitClientChange({
type: "remove",
clientId,
clientCount: this.clients.size,
});
}
notifyClients(event: SseEvent): void {
for (const client of this.clients.values()) {
client.send(event);
}
client.send(event);
}
}
getClientCount(): number {