From 2770d9b07deb662beadb00207114ed9c3764e937 Mon Sep 17 00:00:00 2001 From: marlonerler Date: Thu, 4 Jul 2024 17:27:38 +0200 Subject: [PATCH] add channel communication --- index.ts | 3 --- websocket-handler.ts | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 websocket-handler.ts diff --git a/index.ts b/index.ts index 06c10b8..06799c1 100644 --- a/index.ts +++ b/index.ts @@ -26,9 +26,6 @@ const server = Bun.serve({ }, websocket: { - open(ws) { - - }, message(ws, message) { }, diff --git a/websocket-handler.ts b/websocket-handler.ts new file mode 100644 index 0000000..020211f --- /dev/null +++ b/websocket-handler.ts @@ -0,0 +1,42 @@ +// TYPES +// requests +interface IncomingMessage { + //sent on new connections + connectionType?: ConnectionType; + + // subscribing to channel + channelSubscription?: string; + + //sending message + messageChannel?: string; + messageBody?: string; +} + +// connections +enum ConnectionType { + Server = "server", + Client = "client", +} + +// TRACKING +const serversOnEntireNetwork = new Set(); + +const socketsPerChannel = new Map>(); +const channelsPerSocket = new Map>(); + +export function trackServer(ws: WebSocket): void { + serversOnEntireNetwork.add(ws); +} + +export function trackSubscription(channel: string, ws: WebSocket): void { + if (!socketsPerChannel.has(channel)) socketsPerChannel.set(channel, new Set()); + if (!channelsPerSocket.has(ws)) channelsPerSocket.set(ws, new Set()); + + socketsPerChannel.get(channel)!.add(ws); + channelsPerSocket.get(ws)!.add(channel); +} + +export function forgetConnection(ws: WebSocket): void { + serversOnEntireNetwork.delete(ws); + serversOnEntireNetwork.delete(ws); +}