UNPKG

celeritas

Version:

This is an API service framework which supports API requests over HTTP & WebSockets.

105 lines (85 loc) 2.78 kB
'use strict'; const uuid = require("uuid"); const querystring = require('querystring'); const validator = require('validator'); const lodash = require('lodash'); String.prototype.capitalize = function() { return this.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); }); }; class WebSocketCall { constructor (app, message, client, util) { //Check to make sure the websocket message isn't malformed. if (message instanceof Error) { Object.assign(this, { id: uuid().replace(/-/g, ""), status: util.ERROR, timestamp: new Date().toISOString(), ipAddress: client.ip, error: message, auth: null, output: { code: null, data: null }, wsClient: client }); return this; } var routePath = message.route.substring(message.route.indexOf(" ")); Object.assign(this, { id: message.id, status: util.PENDING, method: message.route.split(" ")[0].toUpperCase(), hostname: client.upgradeReq.headers.host, url: client.upgradeReq.headers.host + routePath, route: routePath.split("?").shift().substring(1).toLowerCase(), post: message.post || {}, rawPost: JSON.stringify(message.post || {}), get: message.get || {}, param: routePath.split("?").shift().substring(1).split("/").pop(), timestamp: new Date().toISOString(), ipAddress: message.ip, returnMimeType: "application/json", returnInput: message.returnInput || false, compression: { //(message.compression) ? (message.compression.indexOf("gzip") > -1 ? "gzip" : null) : null, input: null, output: null }, cache: message.cache || 0, paging: util.assemblePaging(message.get || {}), sort: util.assembleSort(message.get || {}), auth: util.assembleAuth(message.authorization || client.authorization || null), output: { code: null, data: null } }); this._rawPost = lodash.cloneDeep(this.post); this._rawGet = lodash.cloneDeep(this.get); if (validator.isMongoId(this.param)) this.route = (this.route.substr(0, this.route.length - this.param.length)) + "*"; else this.param = null; this.wsMessage = message; this.wsClient = client; } static emit (call) { call.output.data.authorization = (call.auth !== null) ? call.auth.type.capitalize() + " " + call.auth.raw : null; call.output.data.type = "API_CALL"; call.wsClient.authorization = call.output.data.authorization; var emit = call.output.data; if (call.app.api.metaData !== true) { if (emit.error) emit = emit.error; else emit = emit.result; } call.wsClient.send(JSON.stringify(emit)); if (call.output.code < 300) { call.status = call.util.COMPLETE; delete call.app._calls[call.id]; } return Promise.resolve(call.output); } } module.exports = WebSocketCall;