UNPKG

@sodacore/ws

Version:

Sodacore ws is a core plugin that extends the Http plugin offering WebSocket support to the Sodacore framework.

85 lines (84 loc) 2.81 kB
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import { Provide } from '@sodacore/di'; let WsConnections = class WsConnections { constructor() { this.connections = new Map(); } addConnection(id, context) { this.connections.set(id, context); } removeConnection(id) { this.connections.delete(id); } getConnection(id) { return this.connections.get(id); } hasConnection(id) { return this.connections.has(id); } getConnections() { return this.connections; } getConnectionCount() { return this.connections.size; } clearConnections(reason) { for (const connection of this.connections.values()) { connection.close(reason); } this.connections.clear(); } broadcast(command, context = {}) { for (const connection of this.connections.values()) { connection.send(command, context); } } broadcastRaw(data) { for (const connection of this.connections.values()) { connection.sendRaw(data); } } broadcastFor(id, command, context = {}) { if (!Array.isArray(id)) id = [id]; for (const connection of id) { const conn = this.connections.get(connection); if (conn) conn.send(command, context); } } broadcastRawFor(id, data) { if (!Array.isArray(id)) id = [id]; for (const connection of id) { const conn = this.connections.get(connection); if (conn) conn.sendRaw(data); } } broadcastExcept(id, command, context = {}) { if (!Array.isArray(id)) id = [id]; for (const connection of this.connections.values()) { if (!id.includes(connection.getId())) connection.send(command, context); } } broadcastRawExcept(id, data) { if (!Array.isArray(id)) id = [id]; for (const connection of this.connections.values()) { if (!id.includes(connection.getId())) connection.sendRaw(data); } } }; WsConnections = __decorate([ Provide() ], WsConnections); export default WsConnections;