UNPKG

@cashfarm/tractor

Version:

A Hapi server with superpowers

66 lines 2.59 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const tslib_1 = require("tslib"); const hapi_1 = require("hapi"); const inversify_1 = require("inversify"); const interfaces_1 = require("./interfaces"); const endpoint_1 = require("./decorators/endpoint"); const inversify_2 = require("inversify"); const debug = require('debug')('tractor'); exports.IRouter = Symbol.for('@cashfarm/tractor.IRouter'); let Router = class Router { constructor(server, controllers) { this.server = server; this.prefix = ''; this.controllers = []; if (Array.isArray(controllers) && controllers.length) this.addControllers(controllers); } /** * Registers endpoints for the current controllers * * @memberof Router */ addControllers(ctrls) { if (!Array.isArray(ctrls)) throw new Error(`Router.addControllers() expects an array of IController objects, but received ${JSON.stringify(ctrls)}`); this.controllers = this.controllers.concat(this.controllers, ctrls); ctrls.forEach(c => this.addController(c)); } addController(ctrl) { debug(`Adding controller ${ctrl.constructor.name}`); const edpts = Reflect.getMetadata(endpoint_1.EndpointMetadataKey, ctrl.constructor); Reflect.ownKeys(edpts).forEach(epName => { this.registerEndpoint(ctrl, epName, edpts[String(epName)]); }); } registerEndpoint(ctrl, methodKey, meta) { const path = (this.prefix + meta.path).trim().length === 0 ? '/' : (this.prefix + meta.path); this.server.log('debug', `Mapping route ${path} to ${ctrl.constructor.name}.${String(methodKey)}`); this.server.route({ method: meta.method, path: path, config: { description: meta.description, notes: meta.notes, tags: meta.tags, handler: ctrl[methodKey].bind(ctrl), validate: meta.validate, auth: meta.auth } }); } }; tslib_1.__decorate([ inversify_1.inject('ApiPrefix'), tslib_1.__metadata("design:type", Object) ], Router.prototype, "prefix", void 0); Router = tslib_1.__decorate([ inversify_2.injectable(), tslib_1.__param(0, inversify_1.inject(hapi_1.Server)), tslib_1.__param(1, inversify_1.multiInject(interfaces_1.IController)), tslib_1.__metadata("design:paramtypes", [hapi_1.Server, Array]) ], Router); exports.Router = Router; exports.default = Router; //# sourceMappingURL=router.js.map