UNPKG

@chubbyjs/chubbyjs-framework

Version:

A minimal, highly performant middleware PSR-15 microframework built with as little complexity as possible, aimed primarily at those developers who want to understand all the vendors they use.

45 lines (44 loc) 1.71 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const NullLogger_1 = require("@chubbyjs/psr-log/dist/NullLogger"); const Html_1 = require("../Html"); const HttpErrorInterface_1 = require("../Router/Error/HttpErrorInterface"); class RouteMatcherMiddleware { constructor(routeMatcher, responseFactory, logger = new NullLogger_1.default()) { this.routeMatcher = routeMatcher; this.responseFactory = responseFactory; this.logger = logger; } async process(request, handler) { let route; try { route = this.routeMatcher.match(request); } catch (error) { if ((0, HttpErrorInterface_1.isHttpError)(error)) { return this.routeErrorResponse(error); } throw error; } request = request.withAttribute('route', route); route.getAttributes().forEach((value, key) => { request = request.withAttribute(key, value); }); return handler.handle(request); } routeErrorResponse(routerError) { this.logger.info('Route error', { name: routerError.name, message: routerError.message, code: routerError.code, }); const response = this.responseFactory.createResponse(routerError.code).withHeader('Content-Type', 'text/html'); const body = response.getBody(); body.end(Html_1.errorTemplate .replace(/__STATUS__/g, routerError.code.toString()) .replace(/__TITLE__/g, routerError.name) .replace(/__BODY__/g, routerError.message)); return response; } } exports.default = RouteMatcherMiddleware;