add mailboxes

This commit is contained in:
marlon-erler
2024-07-08 21:13:56 +02:00
parent 85164a4e0a
commit b88959e135
16 changed files with 342 additions and 79 deletions
+59 -9
View File
@@ -1,3 +1,9 @@
import {
WebSocketMessage,
sendWebSocketMessage,
subscriptionMap,
} from "./websocket-handler";
import Crypto from "crypto";
import { WS } from "./index";
@@ -6,19 +12,38 @@ export interface Subscriber {
}
export class Mailbox implements Subscriber {
// basic
// basic data
id = Crypto.randomUUID();
dateLastChecked = new Date();
messages = new Set<string>();
get expiryDate() {
const expiryDate = new Date(this.dateLastChecked);
expiryDate.setDate(expiryDate.getDate() + 7);
TODO expiryDate.setDate(expiryDate.getDate() + 7);
return expiryDate;
}
// init
constructor(ws: WS) {
this.ws = ws;
this.sendId();
}
sendId(): void {
if (!this.ws) return;
sendWebSocketMessage(
{
assignedMailboxId: this.id,
},
this.ws
);
}
// storage
messages = new Set<string>();
// websocket
_ws: WS | undefined;
private _ws: WS | undefined;
get ws(): WS | undefined {
return this._ws;
@@ -26,19 +51,36 @@ export class Mailbox implements Subscriber {
set ws(ws: WS) {
this._ws = ws;
this.dateLastChecked = new Date();
this.sendUnreadMessages();
const channels = subscriptionMap.getChannelList(ws);
channels?.forEach((channel) => this.subscribe(channel));
subscriptionMap.deleteSubscriber(ws);
}
// subscribing
subscribe(channelName: string): void {
subscriptionMap.set(this, channelName);
}
unsubscribe(channelName: string): void {
subscriptionMap.delete(this, channelName);
}
// sending
send(message) {
if (this._ws) {
send(message: string): void {
if (this._ws?.readyState == 1) {
this._ws.send(message);
} else {
this.messages.add(message);
}
}
sendUnreadMessages() {
sendUnreadMessages(): void {
console.log(this.messages);
this.messages.forEach((message) => {
if (!this._ws) return;
@@ -96,11 +138,19 @@ export class SubscriptionMap {
}
}
deleteSubscriber(subscriber: Subscriber): void {
this.getChannelList(subscriber)?.forEach((channel) => {
this.delete(subscriber, channel);
});
}
// messages
forwardMessage(channels: string[], messageString: string): void {
forwardMessage(channels: string[], messageObject: WebSocketMessage): void {
channels.forEach((channel) => {
const subscribers = this.getClientList(channel);
subscribers?.forEach((subscriber) => subscriber.send(messageString));
subscribers?.forEach((subscriber) => {
sendWebSocketMessage(messageObject, subscriber);
});
});
}
}