UNPKG

2.3 kBJavaScriptView Raw
1"use strict";
2// Copyright IBM Corp. and LoopBack contributors 2018,2020. 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.compareRoute = void 0;
8const path_to_regexp_1 = require("path-to-regexp");
9/**
10 * Sorting order for http verbs
11 */
12const 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 */
26function compareRoute(route1, route2) {
27 // First check the path tokens
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 // Then check verb
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}
56exports.compareRoute = compareRoute;
57/**
58 *
59 * @param path - Parse a path template into tokens
60 */
61function toTokens(path) {
62 const tokens = [];
63 (0, path_to_regexp_1.parse)(path).forEach(p => {
64 if (typeof p === 'string') {
65 // The string can be /orders/count
66 tokens.push(...p.split('/').filter(Boolean));
67 }
68 else {
69 // Use `{}` for wildcard as they are larger than any other ascii chars
70 tokens.push(`{}`);
71 }
72 });
73 return tokens;
74}
75//# sourceMappingURL=route-sort.js.map
\No newline at end of file