1 | "use strict";
|
2 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
3 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
4 | };
|
5 | Object.defineProperty(exports, "__esModule", { value: true });
|
6 | const path_to_regexp_1 = __importDefault(require("path-to-regexp"));
|
7 | class RouterService {
|
8 | constructor(config) {
|
9 | this.routes = [];
|
10 | this.config = config;
|
11 | this.registerRoutes(this.config.routes);
|
12 | }
|
13 | resolve(method, target) {
|
14 | for (let i = 0; i < this.routes.length; i++) {
|
15 | const route = this.routes[i];
|
16 | if (method !== route.method) {
|
17 | continue;
|
18 | }
|
19 | const parameters = this.match(target, route);
|
20 | if (parameters) {
|
21 | return { route, parameters };
|
22 | }
|
23 | }
|
24 | return null;
|
25 | }
|
26 | match(target, route) {
|
27 | const { regex, keys } = route;
|
28 | const result = regex.exec(target);
|
29 | if (!result) {
|
30 | return null;
|
31 | }
|
32 |
|
33 | result.splice(0, 1);
|
34 | return this.buildParameters(keys, result);
|
35 | }
|
36 | registerRoutes(routes) {
|
37 | routes.forEach(newRoute => {
|
38 | if (Array.isArray(newRoute)) {
|
39 | return this.registerRoutes(newRoute);
|
40 | }
|
41 | const { method, route, action, controller } = newRoute;
|
42 | this.registerRoute(method, route, controller, action);
|
43 | });
|
44 | return this;
|
45 | }
|
46 | registerRoute(method, route, controller, action) {
|
47 | const keys = [];
|
48 | const regex = path_to_regexp_1.default(route, keys);
|
49 | this.routes.push({ regex, controller, action, keys, method, route });
|
50 | return this;
|
51 | }
|
52 | getRegisteredRoutes() {
|
53 | return this.routes;
|
54 | }
|
55 | buildParameters(from, result) {
|
56 | return result.reduce((params, match, index) => {
|
57 | return Object.assign(params, { [from[index].name]: match });
|
58 | }, {});
|
59 | }
|
60 | }
|
61 | exports.RouterService = RouterService;
|
62 |
|
\ | No newline at end of file |