-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.ts
90 lines (74 loc) · 1.95 KB
/
handler.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
87
88
89
90
import { HandleFunc, Matcher } from "./types.ts";
import {
buildPathMatcher,
buildQueryMatcher,
deleteMatcher,
getMatcher,
patchMatcher,
postMatcher,
putMatcher,
} from "./matchers.ts";
import { Request } from "./request.ts";
import { Application } from "./application.ts";
export class Handler {
private matchers: Matcher[] = [];
private handler: (HandleFunc | Application) | null = null;
private isHandlerASubRouter(): boolean {
return this.handler instanceof Application;
}
private runMatchers(req: Request): boolean {
for (let i = 0; i < this.matchers.length; i++) {
const matcher: Matcher = this.matchers[i];
if (!matcher(req, this.isHandlerASubRouter())) return false;
}
return true;
}
private async runHandler(req: Request) {
if (!this.handler) return;
if (this.isHandlerASubRouter()) {
return (this.handler as Application)["runHandlers"](req);
} else {
return (this.handler as HandleFunc)(req);
}
}
private isMiddleware() {
return this.handler !== null && this.matchers.length === 0;
}
private isRoute() {
return this.handler !== null && this.matchers.length > 0;
}
match(custom: Matcher): Handler {
this.matchers.push(custom);
return this;
}
get get(): Handler {
return this.match(getMatcher);
}
get post(): Handler {
return this.match(postMatcher);
}
get put(): Handler {
return this.match(putMatcher);
}
get delete(): Handler {
return this.match(deleteMatcher);
}
get patch(): Handler {
return this.match(patchMatcher);
}
path(urlPath: string): Handler {
return this.match(buildPathMatcher(urlPath));
}
queries(queries: string[]): Handler {
return this.match(buildQueryMatcher(queries));
}
handle(handler: HandleFunc | Application) {
this.handler = handler;
return this;
}
private async run(req: Request) {
if (this.runMatchers(req)) {
return this.runHandler(req);
}
}
}