-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
56 lines (46 loc) · 1.29 KB
/
app.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
import { serve, ServeInit } from "https://deno.land/[email protected]/http/server.ts";
import { isOk } from "./base/result.ts";
import { Route } from "./router/route.ts";
export type Handler<C, T> = (
context: C,
t: T,
request: Request
) => Response | Promise<Response>;
export type Entry<C, T> = {
route: Route<C, T>;
handler: Handler<C, T>;
};
export class App<C> {
// deno-lint-ignore no-explicit-any
private entries: Entry<C, any>[] = [];
constructor(private context: C) {}
public run(init: ServeInit) {
return serve((request: Request) => {
return this.handle(request);
}, init);
}
private async handle(request: Request) {
for (const entry of this.entries) {
const resultOrPromise = entry.route(request, this.context);
const result =
resultOrPromise instanceof Promise
? await resultOrPromise
: resultOrPromise;
if (isOk(result)) {
return entry.handler(this.context, result.value, request);
}
}
const body = JSON.stringify({ message: "NOT FOUND" });
const response = new Response(body, {
status: 404,
});
return response;
}
route<R>(route: Route<C, R>, handler: Handler<C, R>) {
const entry: Entry<C, R> = {
route,
handler,
};
this.entries.push(entry);
}
}