From feb13e8ae717f904a2be7fea461c10731d1f60c0 Mon Sep 17 00:00:00 2001 From: Ian Torres Date: Wed, 18 Jun 2025 19:50:27 -0400 Subject: [PATCH] fix websocket subscription handling --- server/plugins/ws.ts | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/server/plugins/ws.ts b/server/plugins/ws.ts index 851a783..8a79d9a 100644 --- a/server/plugins/ws.ts +++ b/server/plugins/ws.ts @@ -8,7 +8,7 @@ export default defineNitroPlugin((nitroApp) => { console.log('Nitro plugin [Server]') const services = getServices(); - const subscriptions = new Map>() // canal -> conexiones + const subscriptions = new Map>() // channel -> sockets wss.on('connection', (socket) => { let currentChannel: string | null = null @@ -39,6 +39,13 @@ export default defineNitroPlugin((nitroApp) => { callback: callback, })) as StatusResponse; + if (response.success) { + if (!subscriptions.has(currentChannel)) { + subscriptions.set(currentChannel, new Set()); + } + subscriptions.get(currentChannel)!.add(socket); + } + socket.send(JSON.stringify({ event: "SYSTEM", success: response.success, @@ -52,6 +59,15 @@ export default defineNitroPlugin((nitroApp) => { type: RequestType.Unsubscribe, channel: currentChannel!, })) as StatusResponse; + + if (currentChannel) { + const clients = subscriptions.get(currentChannel); + clients?.delete(socket); + if (clients && clients.size === 0) { + subscriptions.delete(currentChannel); + } + } + socket.send(JSON.stringify({ event: "SYSTEM", success: response.success, @@ -60,6 +76,13 @@ export default defineNitroPlugin((nitroApp) => { }) socket.on('close', () => { + if (currentChannel) { + const clients = subscriptions.get(currentChannel) + clients?.delete(socket) + if (clients && clients.size === 0) { + subscriptions.delete(currentChannel) + } + } }) })