Archived
Improve session reconnect behavior
This commit is contained in:
@@ -2,6 +2,7 @@ import type { WebSocket } from "ws";
|
||||
|
||||
export class SessionEventHub {
|
||||
private readonly socketsBySession = new Map<string, Set<WebSocket>>();
|
||||
private readonly globalSockets = new Set<WebSocket>();
|
||||
|
||||
add(sessionId: string, socket: WebSocket): void {
|
||||
let sockets = this.socketsBySession.get(sessionId);
|
||||
@@ -13,10 +14,22 @@ export class SessionEventHub {
|
||||
socket.on("close", () => sockets?.delete(socket));
|
||||
}
|
||||
|
||||
addGlobal(socket: WebSocket): void {
|
||||
this.globalSockets.add(socket);
|
||||
socket.on("close", () => this.globalSockets.delete(socket));
|
||||
}
|
||||
|
||||
publish(sessionId: string, event: unknown): void {
|
||||
const payload = JSON.stringify(event);
|
||||
for (const socket of this.socketsBySession.get(sessionId) ?? []) {
|
||||
if (socket.readyState === socket.OPEN) socket.send(payload);
|
||||
}
|
||||
}
|
||||
|
||||
publishGlobal(event: unknown): void {
|
||||
const payload = JSON.stringify(event);
|
||||
for (const socket of this.globalSockets) {
|
||||
if (socket.readyState === socket.OPEN) socket.send(payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user