1 | "use strict";
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | Object.defineProperty(exports, "__esModule", { value: true });
|
7 | exports.compareRoute = void 0;
|
8 | const path_to_regexp_1 = require("path-to-regexp");
|
9 |
|
10 |
|
11 |
|
12 | const HTTP_VERBS = {
|
13 | post: 1,
|
14 | put: 2,
|
15 | patch: 3,
|
16 | get: 4,
|
17 | head: 5,
|
18 | delete: 6,
|
19 | options: 7,
|
20 | };
|
21 | /**
|
22 | * Compare two routes by verb/path for sorting
|
23 | * @param route1 - First route entry
|
24 | * @param route2 - Second route entry
|
25 | */
|
26 | function compareRoute(route1, route2) {
|
27 |
|
28 | const path1 = route1.path.replace(/{([^}]*)}(\/|$)/g, ':$1$2');
|
29 | const path2 = route2.path.replace(/{([^}]*)}(\/|$)/g, ':$1$2');
|
30 | const tokensForPath1 = toTokens(path1);
|
31 | const tokensForPath2 = toTokens(path2);
|
32 | const length = tokensForPath1.length > tokensForPath2.length
|
33 | ? tokensForPath1.length
|
34 | : tokensForPath2.length;
|
35 | for (let i = 0; i < length; i++) {
|
36 | const token1 = tokensForPath1[i];
|
37 | const token2 = tokensForPath2[i];
|
38 | if (token1 === token2)
|
39 | continue;
|
40 | if (token1 === undefined)
|
41 | return 1;
|
42 | if (token2 === undefined)
|
43 | return -1;
|
44 | if (token1 < token2)
|
45 | return -1;
|
46 | if (token1 > token2)
|
47 | return 1;
|
48 | }
|
49 |
|
50 | const verb1 = HTTP_VERBS[route1.verb.toLowerCase()] || HTTP_VERBS.get;
|
51 | const verb2 = HTTP_VERBS[route2.verb.toLowerCase()] || HTTP_VERBS.get;
|
52 | if (verb1 !== verb2)
|
53 | return verb1 - verb2;
|
54 | return 0;
|
55 | }
|
56 | exports.compareRoute = compareRoute;
|
57 |
|
58 |
|
59 |
|
60 |
|
61 | function toTokens(path) {
|
62 | const tokens = [];
|
63 | (0, path_to_regexp_1.parse)(path).forEach(p => {
|
64 | if (typeof p === 'string') {
|
65 |
|
66 | tokens.push(...p.split('/').filter(Boolean));
|
67 | }
|
68 | else {
|
69 |
|
70 | tokens.push(`{}`);
|
71 | }
|
72 | });
|
73 | return tokens;
|
74 | }
|
75 |
|
\ | No newline at end of file |