-
Notifications
You must be signed in to change notification settings - Fork 0
/
_route.ts
71 lines (65 loc) · 1.51 KB
/
_route.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { pathToRegexp } from "./deps.ts";
export interface Route {
readonly filePath: string;
readonly method: string;
readonly path: string;
readonly regexp: RegExp;
params: (path: string) => Map<string, string>;
}
/**
* Creates a new route object.
*
* @param {string} method
* @param {string} path
* @param {string} filePath
* @returns {Route}
*/
export default function create(
method: string,
path: string,
filePath: string,
): Route {
const glob = path.endsWith("/*");
const cleaned = cleanPath(path);
const keys: pathToRegexp.Key[] = [];
const regexp = pathToRegexp.pathToRegexp(cleaned, keys, {
end: !glob,
});
const matcher = pathToRegexp.match(cleaned);
return {
filePath,
path,
method,
regexp,
params(path: string): Map<string, string> {
const matches = matcher(path);
return new Map(matches ? Object.entries(matches.params) : []);
},
};
}
/**
* Cleans a Serva path into a path-to-regexp path.
*
* @example
* cleanPath("/comments/[comment]");
* // => "/comments/:comment"
*
* cleanPath("/comments/*");
* // => "/comments"
*
* @param {string} path
* @returns {string}
*/
function cleanPath(path: string): string {
let cleaned = path.replace(/\/\*$/, "");
// /[param] => /:param
const split = cleaned.split("[");
if (split.length > 1) {
cleaned = split.reduce(
(res, token, index) =>
[res, index > 0 ? ":" : "", token.replace(/\]/, "")].join(""),
"",
);
}
return cleaned || "/"; // "" => "/"
}