define mailbox

This commit is contained in:
marlon-erler
2024-07-08 19:48:49 +02:00
parent 1b9e1a96ba
commit 85d7a787a1
2 changed files with 42 additions and 6 deletions
+37
View File
@@ -1,9 +1,46 @@
import Crypto from "crypto";
import { WS } from "./index";
export interface Subscriber {
send: (message: string) => void;
}
export class Mailbox implements Subscriber {
// basic
id = Crypto.randomUUID();
messages = new Set<string>();
// websocket
_ws: WS | undefined;
get ws(): WS | undefined {
return this._ws;
}
set ws(ws: WS) {
this._ws = ws;
this.sendUnreadMessages();
}
// sending
send(message) {
if (this._ws) {
this._ws.send(message);
} else {
this.messages.add(message);
}
}
sendUnreadMessages() {
this.messages.forEach((message) => {
if (!this._ws) return;
this._ws.send(message);
this.messages.delete(message);
});
}
}
export class SubscriptionMap {
channelsPerSubscriber = new Map<Subscriber, Set<string>>();
subscribersPerChannel = new Map<string, Set<Subscriber>>();