make clients of sse service observable
This commit is contained in:
22
dist/sse.js
vendored
22
dist/sse.js
vendored
@@ -1,13 +1,35 @@
|
||||
import { logInfo } from "./logger.js";
|
||||
export class SseService {
|
||||
clients = new Map();
|
||||
clientChangeCallbacks = [];
|
||||
onClientChange(callback) {
|
||||
this.clientChangeCallbacks.push(callback);
|
||||
return () => {
|
||||
this.clientChangeCallbacks = this.clientChangeCallbacks.filter((cb) => cb !== callback);
|
||||
};
|
||||
}
|
||||
emitClientChange(event) {
|
||||
for (const callback of this.clientChangeCallbacks) {
|
||||
callback(event);
|
||||
}
|
||||
}
|
||||
addClient(client) {
|
||||
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) {
|
||||
this.clients.delete(clientId);
|
||||
logInfo(`SSE client disconnected: ${clientId}. Total clients: ${this.clients.size}`);
|
||||
this.emitClientChange({
|
||||
type: "remove",
|
||||
clientId,
|
||||
clientCount: this.clients.size,
|
||||
});
|
||||
}
|
||||
notifyClients(event) {
|
||||
for (const client of this.clients.values()) {
|
||||
|
||||
Reference in New Issue
Block a user