UNPKG

@yucom/rest-server

Version:
159 lines 7.39 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const log_1 = __importDefault(require("@yucom/log")); const express_1 = __importDefault(require("express")); const path_proxy_1 = require("./path-proxy"); let serverLog = log_1.default.create('server-app:request-handler'); function asHandler(handler) { if (typeof (handler) === 'function') { return handler; } else { return (() => handler); } } class RequestHandler { constructor(express, router, pathsRecord) { this.express = express; this.router = router; this.pathsRecord = pathsRecord; this.readyPromise = undefined; this.server = undefined; this.getExpressPath = (paths) => paths.map((p, idx) => p.startsWith('$') ? ':var' + idx : p); this.getParams = (paths) => this.getExpressPath(paths).filter(p => p.startsWith(':')).map(p => p.slice(1)); this.getPath = (paths) => '/' + this.getExpressPath(paths).join('/'); this.getParamsValues = (req, params) => params.map(param => req.params[param]); this.getContext = (req, res) => ({ request: req, response: res, args: req.query, headers: req.headers, cookies: req.cookies }); this.initPathHanlder = (onExecute) => path_proxy_1.ProxyPathHandler.create([], onExecute); this.list = this.initPathHanlder((paths, response) => { let handler = asHandler(response); this.registerHandler('get', paths, 200, function (_, ...params) { return __awaiter(this, void 0, void 0, function* () { return yield handler.call(this, ...params); }); }); }); this.get = this.initPathHanlder((paths, response) => { let handler = asHandler(response); this.registerHandler('get', paths, 200, function (_, ...params) { return __awaiter(this, void 0, void 0, function* () { return yield handler.call(this, ...params); }); }); }); this.create = this.initPathHanlder((paths, response) => { let handler = asHandler(response); this.registerHandler('post', paths, 201, function (body, ...params) { return __awaiter(this, void 0, void 0, function* () { return yield handler.call(this, body, ...params); }); }); }); this.replace = this.initPathHanlder((paths, response) => { let handler = asHandler(response); this.registerHandler('put', paths, 201, function (body, ...params) { return __awaiter(this, void 0, void 0, function* () { return yield handler.call(this, body, ...params); }); }); }); this.remove = this.initPathHanlder((paths, response) => { let handler = asHandler(response); this.registerHandler('delete', paths, 204, function (_, ...params) { return __awaiter(this, void 0, void 0, function* () { return yield handler.call(this, ...params); }); }); }); this.update = this.initPathHanlder((paths, response) => { let handler = asHandler(response); this.registerHandler('patch', paths, 201, function (body, ...params) { return __awaiter(this, void 0, void 0, function* () { return yield handler.call(this, body, ...params); }); }); }); this.invoke = this.initPathHanlder((paths, response) => { let handler = asHandler(response); this.registerHandler('post', paths, 200, function (body, ...params) { return __awaiter(this, void 0, void 0, function* () { return yield handler.call(this, body, ...params); }); }); }); this.intercept = this.initPathHanlder((paths, handler) => this.registerInterceptor('use', paths, function (next) { return __awaiter(this, void 0, void 0, function* () { handler.call(this, next); }); })); this.static = this.initPathHanlder((paths, rootFolder) => { const expressPath = this.getPath(paths); serverLog.debug(`Static("${expressPath}")`); router.use(expressPath, express_1.default.static(rootFolder, { fallthrough: false, extensions: ['html', 'htm'] })); }); } ready() { return this.readyPromise || Promise.reject(new Error('Server not started. Use listen.')); } close() { return new Promise((resolve, reject) => { this.server.close((err) => { if (err) reject(err); else resolve(); }); }); } listen(port = 7000) { if (this.server) return Promise.reject(new Error('Cannot restart a server. Not supported.')); this.readyPromise = new Promise(resolve => { this.server = this.express.listen(port, resolve); }); return this.readyPromise; } recordPath(path, method) { serverLog.debug(`Handler(${method.toUpperCase()}, "${path}")`); this.pathsRecord[path] = this.pathsRecord[path] === undefined ? [] : this.pathsRecord[path]; this.pathsRecord[path].push(method); } registerHandler(method, paths, successfulStatus, handler) { const expressPath = this.getPath(paths); const params = this.getParams(paths); this.recordPath(expressPath, method); this.router[method](expressPath, (req, res, next) => { handler.call(this.getContext(req, res), req.body, ...this.getParamsValues(req, params)) .then((result) => { serverLog.info(`Request(path="${req.originalUrl}", body=${JSON.stringify(req.body)}) => ` + `Response(status=${successfulStatus}, body=${JSON.stringify(result)})`); res.status(successfulStatus).json({ data: result }); }) .catch(next); }); } registerInterceptor(method, paths, handler) { const expressPath = this.getPath(paths); serverLog.debug(`Inteceptor("${expressPath}")`); this.router[method](expressPath, (req, res, next) => handler.call(this.getContext(req, res), next).catch(next)); } } exports.RequestHandler = RequestHandler; //# sourceMappingURL=request-handler.js.map