|
1
|
import { pathToRegexp } from "path-to-regexp" |
|
2
|
import type { MiddlewareVerb, RouteVerb } from "./types" |
|
3
|
import { isString } from "@medusajs/utils" |
|
4
|
|
|
5
|
export class RoutesFinder< |
|
6
|
T extends |
|
7
|
| { matcher: string | RegExp; methods: MiddlewareVerb | MiddlewareVerb[] } |
|
8
|
| { matcher: string | RegExp; method: RouteVerb } |
|
9
|
> { |
|
10
|
/** |
|
11
|
* Cache of existing matches to avoid regex tests on every |
|
12
|
* single HTTP request |
|
13
|
*/ |
|
14
|
#existingMatches: Map< |
|
15
|
string, |
|
16
|
| (T & { |
|
17
|
matchRegex: RegExp |
|
18
|
}) |
|
19
|
| null |
|
20
|
> = new Map() |
|
21
|
|
|
22
|
/** |
|
23
|
* Collection of registered routes |
|
24
|
*/ |
|
25
|
#routes: (T & { |
|
26
|
matchRegex: RegExp |
|
27
|
})[] = [] |
|
28
|
|
|
29
|
constructor(routes?: T[]) { |
|
30
|
if (routes) { |
|
31
|
routes.forEach((route) => this.add(route)) |
|
32
|
} |
|
33
|
} |
|
34
|
|
|
35
|
/** |
|
36
|
* Register route for lookup |
|
37
|
*/ |
|
38
|
add(route: T) { |
|
39
|
/** |
|
40
|
* A regular expression matcher is used directly for matching, since |
|
41
|
* path-to-regexp only compiles string paths. |
|
42
|
*/ |
|
43
|
if (route.matcher instanceof RegExp) { |
|
44
|
this.#routes.push({ |
|
45
|
...route, |
|
46
|
matchRegex: route.matcher, |
|
47
|
}) |
|
48
|
return |
|
49
|
} |
|
50
|
|
|
51
|
// Doing a replacement for backwards compatibility with the old path-to-regexp with express 4 |
|
52
|
let normalizedPath = route.matcher |
|
53
|
if (isString(route.matcher)) { |
|
54
|
// Replace /* with {*splat} (wildcard matches zero or more path segments) |
|
55
|
normalizedPath = normalizedPath.replace(/\/\*/g, "{*splat}") |
|
56
|
// Replace /path* (no slash before asterisk) with /path{*splat} |
|
57
|
normalizedPath = normalizedPath.replace(/(\w)\*/g, "$1{*splat}") |
|
58
|
} |
|
59
|
this.#routes.push({ |
|
60
|
...route, |
|
61
|
matchRegex: pathToRegexp(normalizedPath).regexp, |
|
62
|
}) |
|
63
|
} |
|
64
|
|
|
65
|
/** |
|
66
|
* Get the matching route for a given HTTP method and URL |
|
67
|
*/ |
|
68
|
find(url: string, method: MiddlewareVerb) { |
|
69
|
const key = `${method}:${url}` |
|
70
|
if (this.#existingMatches.has(key)) { |
|
71
|
return this.#existingMatches.get(key) |
|
72
|
} |
|
73
|
|
|
74
|
const result = |
|
75
|
this.#routes.find((route) => { |
|
76
|
if ("methods" in route) { |
|
77
|
return route.methods.includes(method) && route.matchRegex.test(url) |
|
78
|
} |
|
79
|
return route.method === method && route.matchRegex.test(url) |
|
80
|
}) ?? null |
|
81
|
|
|
82
|
this.#existingMatches.set(key, result) |
|
83
|
return result |
|
84
|
} |
|
85
|
} |