-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
route.utils.ts
75 lines (66 loc) · 2.15 KB
/
route.utils.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
72
73
74
75
import { RouteMetadata } from "../metadata/route.ts";
import { RouteParam } from "./route.models.ts";
const allowedMethod = (
routeMethod: string,
requestMethod?: string,
): boolean => {
return !requestMethod || routeMethod === requestMethod;
};
/// '/home/test/:id/test' => [{i: 3, el: "id"}]
export const getRouteParams: (route: string) => RouteParam[] = (route) =>
route.split("/").reduce((acc: RouteParam[], el, i) => {
if (/:[A-Za-z1-9]{1,}/.test(el)) {
const result: string = el.replace(":", "");
acc.push({ i, el: result });
}
return acc;
}, []);
/// '/home/test/:id/test' => \/home\/test\/[A-Za-z1-9]{1,}\/test
const getRouteParamPattern: (route: string) => string = (route) =>
route.replace(/\/\:[^/]{1,}/gi, "/[^/]{1,}").replace(/\//g, "\\/");
export const getRouteWithRouteParams = (
routes: RouteMetadata[],
pathname: string,
method?: string,
): any => {
return routes
.filter((r) => r.route.includes("/:") && allowedMethod(r.method, method))
.find((r) => {
return new RegExp("^" + getRouteParamPattern(r.route) + "$").test(
pathname,
);
});
};
export const getRouteFromFullPath = (
routes: RouteMetadata[],
pathname: string,
method?: string,
): RouteMetadata | undefined => {
return routes.find((r) => allowedMethod(r.method, method) && r.route === pathname);
};
export const getRouteWithRegex = (
routes: RouteMetadata[],
pathname: string,
method?: string,
): any => {
return routes
.filter((r) => r.regexpRoute && allowedMethod(r.method.toString(), method))
.find((r) => {
const baseRouteRegex: RegExp = new RegExp("^" + r.route);
return baseRouteRegex.test(pathname) &&
// @ts-ignore: Object is possibly 'null'.
r.regexpRoute.test(pathname.replace(baseRouteRegex, ""));
});
};
export function getPathNameFromUrl(url: string): string {
return getParsedUrl(url).pathname;
}
const parsedUrlMap: Map<string, URL> = new Map<string, URL>();
// TODO: use normal parser
// need for parse
export function getParsedUrl(url: string): URL {
if (!parsedUrlMap.has(url)) {
parsedUrlMap.set(url, new URL(url));
}
return parsedUrlMap.get(url) as URL;
}