-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.ts
86 lines (78 loc) · 2.22 KB
/
router.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
76
77
78
79
80
81
82
83
84
85
86
import { Middleware, reduce } from './middleware.ts';
import { Context } from './context.ts';
export enum Method {
ALL = '*',
GET = 'GET',
POST = 'POST',
DELETE = 'DELETE',
PATCH = 'PATCH',
PUT = 'PUT',
OPTIONS = 'OPTIONS',
HEAD = 'HEAD',
}
export type RouteMatch = Record<string, string | undefined> & {
$: string[];
};
export type RouteHandler = (
ctx: Context,
match: RouteMatch
) => Promise<void> | void;
export class Router {
routes = new Map<string, Middleware>();
constructor(readonly prefix = '') {}
all(path: string, handler: RouteHandler) {
return this.route(Method.ALL, path, handler);
}
get(path: string, handler: RouteHandler) {
return this.route(Method.GET, path, handler);
}
post(path: string, handler: RouteHandler) {
return this.route(Method.POST, path, handler);
}
delete(path: string, handler: RouteHandler) {
return this.route(Method.DELETE, path, handler);
}
patch(path: string, handler: RouteHandler) {
return this.route(Method.PATCH, path, handler);
}
put(path: string, handler: RouteHandler) {
return this.route(Method.PUT, path, handler);
}
options(path: string, handler: RouteHandler) {
return this.route(Method.OPTIONS, path, handler);
}
head(path: string, handler: RouteHandler) {
return this.route(Method.HEAD, path, handler);
}
route(method: string, path: string, handler: RouteHandler) {
method = method.toUpperCase();
const pathname = `${this.prefix}${path}`;
this.routes.set(`${method} ${pathname}`, async (ctx, next) => {
if (
method === Method.ALL ||
method === ctx.request.method.toUpperCase()
) {
const match = ctx.URL.pathname.match(`^${pathname}$`);
if (match)
return await handler(ctx, {
...match.groups,
$: match.slice(1),
} as RouteMatch);
}
await next();
});
return this;
}
unroute(method: string, path: string) {
method = method.toUpperCase();
const pathname = `${this.prefix}${path}`;
this.routes.delete(`${method} ${pathname}`);
return this;
}
handle(): Middleware {
return async (ctx, next) => {
await next();
await reduce([...this.routes.values()])(ctx);
};
}
}