UNPKG

@hyperflake/socket-broker

Version:
86 lines 3.48 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SocketBroker = void 0; const http_1 = require("http"); const socket_io_1 = require("socket.io"); const utils_1 = require("../utils"); const defaultSocketBrokerOptions = { cors: { origin: '*', credentials: true, }, connectionStateRecovery: { // the backup duration of the sessions and the packets maxDisconnectionDuration: 2 * 60 * 1000, // whether to skip middlewares upon successful recovery skipMiddlewares: true, }, authenticationType: 'none', }; class SocketBroker { constructor(options = defaultSocketBrokerOptions) { const { authenticationType, auth, ...rest } = options; this.httpServer = (0, http_1.createServer)(); this.socketServer = new socket_io_1.Server(this.httpServer, { ...rest }); this.socketList = new utils_1.SocketList(); this.authenticationType = authenticationType; this.auth = auth; this.init(); } init() { if (this.authenticationType === 'keyAndSecret') { this.socketServer.use(this.authKeyAndSecretAuthentication.bind(this)); } this.socketServer.on('connection', (socket) => { this.onSocketConnect(socket); socket.onAny((eventName, ...args) => { this.onSocketEvent(eventName, ...args); }); socket.on('disconnect', () => { this.onSocketDisconnect(socket); }); }); } authKeyAndSecretAuthentication(socket, next) { var _a, _b; const { key, secret } = socket.handshake.auth; if (!key || !secret) { return next(new Error('Authentication error: Missing authKey or authSecret')); } // Validate authKey and authSecret if (key !== ((_a = this.auth) === null || _a === void 0 ? void 0 : _a.key) || secret !== ((_b = this.auth) === null || _b === void 0 ? void 0 : _b.secret)) { return next(new Error('Authentication error: Invalid authKey or authSecret')); } next(); // Allow the connection } onSocketConnect(socket) { if (socket.handshake.query.groupId) { // If the connecting socket has a groupId, add the socket to that group utils_1.logger.log(`Socket connected - [SocketId]:${socket.id}, [GroupId]:${socket.handshake.query.groupId}.`); this.socketList.addToGroup(socket.handshake.query.groupId, socket.id); } else { utils_1.logger.log(`Socket connected - [SocketId]:${socket.id}.`); this.socketList.add(socket.id); } } onSocketEvent(eventName, ...args) { const socketIds = this.socketList.getUniqueSockets(); this.socketServer.to(socketIds).emit(eventName, ...args); } onSocketDisconnect(socket) { if (socket.handshake.query.groupId) { utils_1.logger.warn(`Socket disconnected - [SocketId]:${socket.id}, [GroupId]:${socket.handshake.query.groupId}`); this.socketList.deleteFromGroup(socket.handshake.query.groupId, socket.id); } else { utils_1.logger.warn(`Socket disconnected - [SocketId]:${socket.id}`); this.socketList.delete(socket.id); } } listen(port, cb) { this.httpServer.listen(port, cb); } } exports.SocketBroker = SocketBroker; //# sourceMappingURL=socket-broker.js.map