UNPKG

@ords/modules

Version:

Modules for ords-core microservices based upon proposals

89 lines (88 loc) 2.85 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const core_1 = require("@ords/core"); const rxjs_1 = require("rxjs"); const express = require("express"); const bodyParser = require("body-parser"); /** * Express REST map connector */ class MapExpressDatabaseRest { /** * Construct new instance on the specific set of services */ constructor(mserver, connector) { /** * Maps to instance of db */ this.root = 'db'; /** * Name mapping of HTTP */ this.nameMap = { post: 'create', put: 'update', delete: 'delete', get: 'read', patch: 'patch' }; // create router on instance should it map differently?? connector.maps.push(express.Router().all('/db/:resource/', bodyParser.json(), this.bridge.bind(this))); // save instance ref this.msever = mserver; } /** * Forward the request and send back the response between the micro services */ bridge(req, res) { // create package let requestPackage = { query: req.query, runValidations: true, resource: req.params.resource }; // find the method req.method = req.method.toLowerCase(); // set name let name = this.nameMap[req.method]; // check if method requires body if (['patch', 'post', 'put'].indexOf(req.method) !== -1) { // merge files with body if any exists on key _files if (req.files != undefined) { // loop all files for (let file in req.files) { // save ref req.body['_files'][file] = req.files[file]; } } // set reference to data requestPackage.data = req.body; } // create an observable request let request = { package: rxjs_1.Observable.pairs(requestPackage), auth: req.auth }; // perform the action core_1.ShortenAct.tryCatch(this.msever, this.root, name, request, (err, out, meta) => { if (err) { res.status(404).send(err.toString()); } else { // set header from meta Object.keys(meta).forEach((key) => { // bind key values of meta res.header(key, meta[key]); }); // check datatype of results if (Number.isInteger(out)) { res.send(out.toString()); } else { res.send(out); } } }); } } exports.MapExpressDatabaseRest = MapExpressDatabaseRest;