-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
63 lines (56 loc) · 1.55 KB
/
mod.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
export type RouteHandler<Params extends string = string> = (
req: Request,
params?: Partial<Record<Params, string>>,
) => Promise<Response> | Response;
export type RouteMap = Record<
string,
RouteHandler | Record<string, RouteHandler>
>;
function methods(routes: Record<string, RouteHandler>): RouteHandler {
return (req, params) => {
if (req.method in routes) {
return routes[req.method](req, params);
} else {
return new Response(null, { status: 405 });
}
};
}
/**
* Creates router handler with RouteMap config
*
* ```ts
* const router = createRouter({
* '/api/projects': { // Different methods
* 'GET': getProjects,
* 'POST': createProject
* },
* '/api/projects/:id': {
* 'GET': (req, params) => getProject(req, params) // { id: 'abd2193df12c' }
* },
* '/api/check': check, // Any method
* })
*
* await serve(router);
* ```
*/
export function createRouter(routeMap: RouteMap) {
const routes = new Map<URLPattern, RouteHandler>();
for (const route in routeMap) {
const url = new URLPattern({ pathname: route });
const handleDefintion = routeMap[route];
if (typeof handleDefintion === "function") {
routes.set(url, handleDefintion);
} else {
routes.set(url, methods(handleDefintion));
}
}
return (req: Request) => {
for (const [pattern, handler] of routes) {
if (pattern.test(req.url)) {
const params = pattern.exec(req.url)?.pathname.groups;
return handler(req, params);
}
}
return new Response(null, { status: 404 });
};
}