import { IChassisContext } from "../interfaces"; import * as assert from "assert"; import * as _ from "lodash"; import * as uuidv5 from "uuidv5"; export default class Utils { public static deleteJSON(model: any, json_path_node?: any) { this._deleteNodePath(model, json_path_node); return model; } public static _deleteNodePath(model: any, json_path_node: any) { let found = model; let _path = json_path_node.path; for (let n in _path) { let key = _path[n]; if (n == "" + (_path.length - 1)) { delete found[key]; } if (key == "$") found = model; else found = found[key]; } // console.warn("_deleteNodePath: %j --> %j", json_path_node, found); return found; } public static transformByRule(item_or_items, rules, fn) { // normalize single objects into arrays let items = Array.isArray(item_or_items) ? item_or_items : [item_or_items]; // process every item in the array for (let i = 0; i < items.length; i++) { let item = items[i]; for (let r = 0; r < rules.length; r++) { let rule = rules[r]; // apply the external 'transformer' function fn(rule, item, items); } } return items; } public static sendError(context: IChassisContext, res: any, payload: any) { assert(res, "missing http.response"); assert(payload, "missing payload"); assert(payload.code, "missing payload.code"); // assert(payload.statusCode, "missing payload.statusCode"); // assert(payload.message, "missing payload.message"); try { context.warn({ message: payload.message, code: payload.code }); // format and send response res.status(payload.statusCode || 400); res.send({ code: payload.code, message: payload.message }); } catch (e) { context.bus.emit("error", e); return false; } return true; } public static uuid(thing: string) { let privns = uuidv5("null", "a6s", true); return uuidv5(privns, thing); } }