UNPKG

actionhero

Version:

The reusable, scalable, and quick node.js API server for stateless and stateful applications

230 lines (229 loc) 9.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Connection = exports.connectionVerbs = void 0; const uuid = require("uuid"); const index_1 = require("./../index"); const config_1 = require("./../modules/config"); exports.connectionVerbs = [ "quit", "exit", "paramAdd", "paramDelete", "paramView", "paramsView", "paramsDelete", "roomAdd", "roomLeave", "roomView", "detailsView", "say", ]; /** * The generic representation of a connection for all server types is an Actionhero.Connection. You will never be creating these yourself via an action or task, but you will find them in your Actions and Action Middleware. */ class Connection { /** * @param data The specifics of this connection * @param callCreateMethods The specifics of this connection will calls create methods in the constructor. This property will exist for backward compatibility. If you want to construct connection and call create methods within async, you can use `await Actionhero.Connection.createAsync(details)` for construction. */ constructor(data, callCreateMethods = true) { this.setup(data); if (callCreateMethods) Connection.callConnectionCreateMethods(this); index_1.api.connections.connections[this.id] = this; } /** * @param data The specifics of this connection */ static async createAsync(data) { const connection = new this(data, false); await this.callConnectionCreateMethods(connection); return connection; } static async callConnectionCreateMethods(connection) { for (const i in index_1.api.connections.globalMiddleware) { const middlewareName = index_1.api.connections.globalMiddleware[i]; if (typeof index_1.api.connections.middleware[middlewareName].create === "function") { await index_1.api.connections.middleware[middlewareName].create(connection); } } } setup(data) { var _a, _b, _c, _d, _e, _f, _g; ["type", "rawConnection"].forEach((req) => { if (!data[req]) { throw new Error(`${req} is required to create a new connection object`); } }); if (config_1.config.general.enforceConnectionProperties) { if (!data.remotePort && ((_a = data.remotePort) === null || _a === void 0 ? void 0 : _a.toString()) !== "0") throw new Error("remotePort is required to create a new connection object"); if (!data.remoteIP && ((_b = data.remoteIP) === null || _b === void 0 ? void 0 : _b.toString()) !== "0") throw new Error("remoteIP is required to create a new connection object"); this.type = data.type; this.rawConnection = data.rawConnection; this.id = (_c = data.id) !== null && _c !== void 0 ? _c : this.generateID(); this.fingerprint = (_d = data.fingerprint) !== null && _d !== void 0 ? _d : this.id; this.remotePort = (_e = data.remotePort) !== null && _e !== void 0 ? _e : 0; this.remoteIP = (_f = data.remoteIP) !== null && _f !== void 0 ? _f : "0"; this.messageId = (_g = data.messageId) !== null && _g !== void 0 ? _g : "0"; this.connectedAt = new Date().getTime(); this.error = null; this.rooms = []; this.params = {}; this.session = {}; this.pendingActions = 0; this.totalActions = 0; this.canChat = data["canChat"]; this.destroyed = false; const server = index_1.api.servers.servers[this.type]; if (server && server.connectionCustomMethods) { for (const [name] of Object.entries(server.connectionCustomMethods)) { //@ts-ignore this.set(name, async (...args) => { args.unshift(this); return server.connectionCustomMethods[name].apply(null, args); }); } } } } /** * Send a file to a connection (usually in the context of an Action). Be sure to set `data.toRender = false` in the action! * Uses Server#processFile and will set `connection.params.file = path` */ async sendFile(path) { throw new Error("not implemented"); } /** * Send a message to a connection. Uses Server#sendMessage. */ async sendMessage(message, verb) { throw new Error("not implemented"); } generateID() { return uuid.v4(); } /** * Destroys the connection. If the type/sever of the connection has a goodbye message, it will be sent. The connection will be removed from all rooms. The connection's socket will be closed when possible. */ async destroy() { this.destroyed = true; for (const i in index_1.api.connections.globalMiddleware) { const middlewareName = index_1.api.connections.globalMiddleware[i]; if (typeof index_1.api.connections.middleware[middlewareName].destroy === "function") { await index_1.api.connections.middleware[middlewareName].destroy(this); } } if (this.canChat === true) { const promises = []; for (const i in this.rooms) { const room = this.rooms[i]; promises.push(index_1.chatRoom.removeMember(this.id, room)); } await Promise.all(promises); } const server = index_1.api.servers.servers[this.type]; if (server) { if (server.attributes.logExits === true) { server.log("connection closed", "info", { to: this.remoteIP }); } if (typeof server.goodbye === "function") { server.goodbye(this); } } delete index_1.api.connections.connections[this.id]; } set(key, value) { this[key] = value; } /** * Try to run a verb command for a connection */ async verbs(verb, words) { let key; let value; let room; const server = index_1.api.servers.servers[this.type]; const allowedVerbs = server.attributes.verbs; if (!Array.isArray(words)) words = [words]; if (server && allowedVerbs.indexOf(verb) >= 0) { server.log("verb", "debug", { verb: verb, to: this.remoteIP, params: JSON.stringify(words), }); // TODO: investigate allowedVerbs being an array of Constants or Symbols switch (verb) { case "quit": case "exit": return this.destroy(); case "paramAdd": key = words[0]; value = words[1]; if (words[0] && words[0].indexOf("=") >= 0) { const parts = words[0].split("="); key = parts[0]; value = parts[1]; } if (config_1.config.general.disableParamScrubbing || index_1.api.params.postVariables.indexOf(key) >= 0) { this.params[key] = value; } return; case "paramDelete": key = words[0]; delete this.params[key]; return; case "paramView": key = words[0]; return this.params[key]; case "paramsView": return this.params; case "paramsDelete": for (const i in this.params) { delete this.params[i]; } return; case "roomAdd": room = words[0]; return index_1.chatRoom.addMember(this.id, room); case "roomLeave": room = words[0]; return index_1.chatRoom.removeMember(this.id, room); case "roomView": room = words[0]; if (this.rooms.indexOf(room) >= 0) { return index_1.chatRoom.roomStatus(room); } throw new Error(await config_1.config.errors.connectionNotInRoom(this, room)); case "detailsView": return { id: this.id, fingerprint: this.fingerprint, remoteIP: this.remoteIP, remotePort: this.remotePort, params: this.params, connectedAt: this.connectedAt, rooms: this.rooms, totalActions: this.totalActions, pendingActions: this.pendingActions, }; case "documentation": return index_1.api.documentation.documentation; case "say": room = words.shift(); await index_1.api.chatRoom.broadcast(this, room, words.join(" ")); return; } const error = new Error(await config_1.config.errors.verbNotFound(this, verb)); throw error; } else { const error = new Error(await config_1.config.errors.verbNotAllowed(this, verb)); throw error; } } } exports.Connection = Connection;