UNPKG

2.95 kBJavaScriptView Raw
1"use strict";
2// Copyright IBM Corp. and LoopBack contributors 2018,2019. All Rights Reserved.
3// Node module: @loopback/rest
4// This file is licensed under the MIT License.
5// License text available at https://opensource.org/licenses/MIT
6Object.defineProperty(exports, "__esModule", { value: true });
7exports.RegExpRouter = void 0;
8const tslib_1 = require("tslib");
9const core_1 = require("@loopback/core");
10const path_to_regexp_1 = require("path-to-regexp");
11const util_1 = require("util");
12const keys_1 = require("../keys");
13const openapi_path_1 = require("./openapi-path");
14const route_entry_1 = require("./route-entry");
15const route_sort_1 = require("./route-sort");
16const router_base_1 = require("./router-base");
17const debug = require('debug')('loopback:rest:router:regexp');
18/**
19 * Router implementation based on regexp matching
20 */
21let RegExpRouter = class RegExpRouter extends router_base_1.BaseRouter {
22 _sort() {
23 if (!this._sorted) {
24 this.routes.sort(route_sort_1.compareRoute);
25 this._sorted = true;
26 }
27 }
28 constructor(options) {
29 super(options);
30 this.routes = [];
31 }
32 addRouteWithPathVars(route) {
33 const path = (0, openapi_path_1.toExpressPath)(route.path);
34 const keys = [];
35 const regexp = (0, path_to_regexp_1.pathToRegexp)(path, keys, {
36 strict: this.options.strict,
37 end: true,
38 });
39 const entry = Object.assign(route, { keys, regexp });
40 this.routes.push(entry);
41 this._sorted = false;
42 }
43 findRouteWithPathVars(verb, path) {
44 this._sort();
45 for (const r of this.routes) {
46 debug('trying endpoint %s', (0, util_1.inspect)(r, { depth: 5 }));
47 if (r.verb !== verb.toLowerCase()) {
48 debug(' -> verb mismatch');
49 continue;
50 }
51 const match = r.regexp.exec(path);
52 if (!match) {
53 debug(' -> path mismatch');
54 continue;
55 }
56 const pathParams = this._buildPathParams(r, match);
57 debug(' -> found with params: %j', pathParams);
58 return (0, route_entry_1.createResolvedRoute)(r, pathParams);
59 }
60 return undefined;
61 }
62 listRoutesWithPathVars() {
63 this._sort();
64 return this.routes;
65 }
66 _buildPathParams(route, pathMatch) {
67 const pathParams = {};
68 for (const ix in route.keys) {
69 const key = route.keys[ix];
70 const matchIndex = +ix + 1;
71 pathParams[key.name] = pathMatch[matchIndex];
72 }
73 return pathParams;
74 }
75};
76exports.RegExpRouter = RegExpRouter;
77exports.RegExpRouter = RegExpRouter = tslib_1.__decorate([
78 tslib_1.__param(0, (0, core_1.inject)(keys_1.RestBindings.ROUTER_OPTIONS, { optional: true })),
79 tslib_1.__metadata("design:paramtypes", [Object])
80], RegExpRouter);
81//# sourceMappingURL=regexp-router.js.map
\No newline at end of file