UNPKG

bun-ws-router

Version:

A simple and efficient WebSocket router for Bun with Zod/Valibot message validation.

57 lines 2.17 kB
/* SPDX-FileCopyrightText: 2025-present Kriasoft */ /* SPDX-License-Identifier: MIT */ /** * Handles WebSocket connection lifecycle events (open/close). */ export class ConnectionHandler { openHandlers = []; closeHandlers = []; addOpenHandler(handler) { this.openHandlers.push(handler); } addCloseHandler(handler) { this.closeHandlers.push(handler); } handleOpen(ws, send) { const clientId = ws.data.clientId; console.log(`[ws] Connection opened: ${clientId}`); const context = { ws, send }; // Execute all registered open handlers this.openHandlers.forEach((handler) => { try { const result = handler(context); // Handle async handlers if they return a promise if (result instanceof Promise) { result.catch((error) => { console.error(`Unhandled promise rejection in open handler for ${clientId}:`, error); }); } } catch (error) { console.error(`Error in open handler for ${clientId}:`, error); } }); } handleClose(ws, code, reason, send) { const clientId = ws.data.clientId; console.log(`[ws] Connection closed: ${clientId} (Code: ${code}, Reason: ${reason || "N/A"})`); const context = { ws, code, reason, send }; // Execute all registered close handlers this.closeHandlers.forEach((handler) => { try { const result = handler(context); // Handle async handlers if they return a promise if (result instanceof Promise) { result.catch((error) => { console.error(`[ws] Unhandled promise rejection in close handler for ${clientId}:`, error); }); } } catch (error) { // Catch synchronous errors in handlers console.error(`[ws] Error in close handler for ${clientId}:`, error); } }); } } //# sourceMappingURL=connection.js.map