make clients of sse service observable
This commit is contained in:
@@ -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;
|
||||
}
|
||||
};
|
||||
|
||||
42
src/sse.ts
42
src/sse.ts
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user