Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion server/plugins/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default defineNitroPlugin((nitroApp) => {
console.log('Nitro plugin [Server]')
const services = getServices();

const subscriptions = new Map<string, Set<WebSocket>>() // canal -> conexiones
const subscriptions = new Map<string, Set<WebSocket>>() // channel -> sockets

wss.on('connection', (socket) => {
let currentChannel: string | null = null
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand All @@ -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)
}
}
})
})

Expand Down