UNPKG

dlovely-websocket

Version:

WebSocket For Dlovely

100 lines (99 loc) 3.65 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.socketControl = exports.SocketControl = void 0; const SocketCache_1 = require("./SocketCache"); const common_1 = require("./common"); class SocketControl { name; constructor(name) { this.name = name; } _connections = new Map(); get connections() { return [...this._connections.values()]; } has(conn) { if (typeof conn !== 'string') conn = conn.token; return this._connections.has(conn); } tigger = new Map(); static DISCONNECT_KEEPTIME = 10 * 1000; mount(conn, dura = 0) { this._connections.set(conn.token, conn); this.tigger.forEach(event => event(conn)); common_1.toast.log(`已为连接${conn.token}设置角色:${this.name}`); conn.once('close', () => setTimeout(() => this.unmount(conn), SocketControl.DISCONNECT_KEEPTIME)); conn.once('error', () => setTimeout(() => this.unmount(conn), SocketControl.DISCONNECT_KEEPTIME)); if (dura) { let timer = setTimeout(() => { this.unmount(conn); timer = null; }, dura); const { keepRole } = conn.extraParams; conn.extraParams.keepRole = () => { keepRole?.(); timer && clearTimeout(timer); timer = setTimeout(() => { this.unmount(conn); timer = null; }, dura); }; } } unmount(conn) { this._connections.delete(conn.token); common_1.toast.log(`已为连接${conn.token}移除角色:${this.name}`); } broadcast(event) { common_1.toast.log(`正在为所有${this.name}角色的连接进行广播`); this._connections.forEach(conn => event(conn)); common_1.toast.log(`${this.name}角色广播结束`); } stores = {}; defineCache(name, init, key) { if (name in this.stores) common_1.toast.error(`${name}缓存器已存在,请勿重复添加`); return (this.stores[name] = new SocketCache_1.SocketCache(name, init, key, this)); } } exports.SocketControl = SocketControl; const socketControlGroup = { default: new SocketControl('default') }; exports.socketControl = { get group() { return Object.keys(socketControlGroup); }, get connections() { return socketControlGroup.default.connections; }, broadcast(event, ...roles) { if (roles.length) new Set(roles).forEach(role => role in socketControlGroup && socketControlGroup[role].broadcast(event)); else socketControlGroup.default.broadcast(event); }, isRoles(conn, role) { return role in socketControlGroup && socketControlGroup[role].has(conn); }, setRoles(conn, roles, dura = 0) { if (!roles || roles.length == 0) return; if (!Array.isArray(roles)) roles = [roles]; new Set(roles).forEach(role => { if (!(role in socketControlGroup)) socketControlGroup[role] = new SocketControl(role); socketControlGroup[role]?.mount(conn, dura); }); }, defineCache(role, name, init, key) { if (!role) role = 'default'; if (!(role in socketControlGroup)) socketControlGroup[role] = new SocketControl(role); return socketControlGroup[role].defineCache(name, init, key); } };