UNPKG

@nodearch/express

Version:
73 lines 3.27 kB
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { Service } from '@nodearch/core'; import { ErrorRegistry } from '../errors/error-registry.js'; import { InternalServerError } from '../errors/http-errors.js'; import { RouteHandlerParam } from './enums.js'; let RouteHandler = class RouteHandler { constructor(errorRegistry) { this.errorRegistry = errorRegistry; } create(controllerMethodName, inputs) { return (req, res) => { const params = this.getHandlerParams(req, res, inputs); const handler = req.nodearch.controller[controllerMethodName].bind(req.nodearch.controller); handler(...params) .then((result) => { if (res.headersSent) return; if (result) return res.send(result); this.errorRegistry.handleError(new InternalServerError('A route handler was called, but no response was returned.', [ `Controller: ${req.nodearch.controller.constructor.name}`, `Method: ${controllerMethodName}`, `Endpoint: ${req.method} ${req.path}` ]), res); }) .catch((err) => { this.errorRegistry.handleError(err, res); }); }; } getHandlerParams(req, res, inputs) { return inputs .sort((a, b) => a.index - b.index) .map(input => { let param; switch (input.type) { case RouteHandlerParam.REQ: param = req; break; case RouteHandlerParam.RES: param = res; break; case RouteHandlerParam.BODY: param = input.key ? req.body[input.key] : req.body; break; case RouteHandlerParam.HEADERS: param = input.key ? req.headers[input.key] : req.headers; break; case RouteHandlerParam.PARAMS: param = input.key ? req.params[input.key] : req.params; break; case RouteHandlerParam.QUERY: param = input.key ? req.query[input.key] : req.query; break; } return param; }); } }; RouteHandler = __decorate([ Service(), __metadata("design:paramtypes", [ErrorRegistry]) ], RouteHandler); export { RouteHandler }; //# sourceMappingURL=route-handler.js.map