-
Notifications
You must be signed in to change notification settings - Fork 29
/
findRoute.ts
48 lines (41 loc) · 1.35 KB
/
findRoute.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
import { Key } from 'path-to-regexp';
import { HandlerMethod, HttpMethod, HTTP_METHOD_TOKEN } from '../decorators';
import { loadPackage } from './loadPackage';
export function findRoute(
cls: Record<string, any>,
requestMethod: string,
path: string
): [Key[], RegExpExecArray | null | undefined, HandlerMethod | undefined] {
const methods: Array<HandlerMethod> = Reflect.getMetadata(HTTP_METHOD_TOKEN, cls);
const { pathToRegexp } = loadPackage('path-to-regexp');
if (!pathToRegexp) {
const method = methods.find(
f =>
f.path === path &&
(f.method === requestMethod || f.options?.extraMethods?.includes(requestMethod as HttpMethod))
);
return [
[],
undefined,
method ??
methods.find(
f =>
f.path === '/' &&
(f.method === requestMethod || f.options?.extraMethods?.includes(requestMethod as HttpMethod))
)
];
}
const keys: Key[] = [];
let match: RegExpExecArray | null | undefined;
const method = methods.find(f => {
match = pathToRegexp(f.path, keys).exec(path);
const condition =
(f.method === requestMethod || f.options?.extraMethods?.includes(requestMethod as HttpMethod)) && match?.length;
if (!condition) {
keys.length = 0;
match = undefined;
}
return condition;
});
return [keys, match, method];
}