UNPKG

@plumier/core

Version:

Delightful Node.js Rest Framework

65 lines (64 loc) 2.51 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.router = void 0; const path_to_regexp_1 = require("path-to-regexp"); const application_pipeline_1 = require("./application-pipeline"); const common_1 = require("./common"); const types_1 = require("./types"); // --------------------------------------------------------------------- // // ------------------------------- HELPER ------------------------------ // // --------------------------------------------------------------------- // function sendError(ctx, status, message) { ctx.status = status; ctx.body = { status, message }; } function getHandler(ctx) { for (const route of ctx.routes) { if (route.method !== ctx.method.toLowerCase()) continue; const keys = []; const regexp = (0, path_to_regexp_1.pathToRegexp)(route.url, keys); const match = regexp.exec(ctx.path); if (match) return { route, keys, match }; } } function createQuery({ keys, match }) { return keys.reduce((a, b, i) => { a[b.name] = match[i + 1]; return a; }, {}); } /* ------------------------------------------------------------------------------- */ /* ------------------------------- ROUTER ---------------------------------------- */ /* ------------------------------------------------------------------------------- */ function router(infos, config) { const getKey = (ctx) => `${ctx.method}${ctx.path}`; const getHandlerCached = (0, common_1.memoize)(getHandler, getKey); const createPipe = (0, common_1.memoize)(application_pipeline_1.createPipes, getKey); return async (ctx) => { try { ctx.config = config; ctx.routes = infos; ctx.state.caller = "system"; const handler = getHandlerCached(ctx); if (handler) { if (ctx.request.addQuery) ctx.request.addQuery(createQuery(handler)); ctx.route = handler.route; } const pipe = createPipe(ctx); const result = await pipe.execute(ctx).proceed(); await result.execute(ctx); } catch (e) { if (e instanceof types_1.ValidationError) sendError(ctx, e.status, e.issues); else if (e instanceof types_1.HttpStatusError) sendError(ctx, e.status, e.message); else ctx.throw(e); } }; } exports.router = router;