36 lines
1.2 KiB
TypeScript
36 lines
1.2 KiB
TypeScript
import type { SseConnection } from "./sse-connection.js";
|
|
|
|
export interface SseRegistryPort {
|
|
add(sessionId: string, connection: SseConnection): void;
|
|
remove?(sessionId: string, connection: SseConnection): void;
|
|
closeForSession(sessionId: string): void;
|
|
closeAll(): void;
|
|
}
|
|
|
|
export class SseRegistry implements SseRegistryPort {
|
|
readonly #connections = new Map<string, Set<SseConnection>>();
|
|
|
|
public add(sessionId: string, connection: SseConnection): void {
|
|
const existing = this.#connections.get(sessionId);
|
|
if (existing !== undefined) existing.add(connection);
|
|
else this.#connections.set(sessionId, new Set([connection]));
|
|
}
|
|
|
|
public remove(sessionId: string, connection: SseConnection): void {
|
|
const existing = this.#connections.get(sessionId);
|
|
existing?.delete(connection);
|
|
if (existing?.size === 0) this.#connections.delete(sessionId);
|
|
}
|
|
|
|
public closeForSession(sessionId: string): void {
|
|
const connections = this.#connections.get(sessionId);
|
|
if (connections === undefined) return;
|
|
this.#connections.delete(sessionId);
|
|
for (const connection of [...connections]) connection.close();
|
|
}
|
|
|
|
public closeAll(): void {
|
|
for (const sessionId of [...this.#connections.keys()]) this.closeForSession(sessionId);
|
|
}
|
|
}
|