This repository has been archived by the owner on Jul 29, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.ts
84 lines (75 loc) · 1.67 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
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
import {
ConnInfo,
Handler,
serve,
ServeInit,
} from "https://deno.land/std@0.168.0/http/server.ts";
/**
* Default handler for unsupported methods.
* @returns Default response.
*/
const defaultHandler: Handler = (_: Request) =>
Promise.resolve(
new Response(
"Method not allowed",
{
status: 405,
},
),
);
class App {
/**
* Handlers for each HTTP method.
*/
private handlers: Map<string, Handler> = new Map();
/**
* Register a handler for HEAD method.
* @param handler Handler for HEAD method.
*/
head(handler: Handler) {
this.handlers.set("HEAD", handler);
}
/**
* Register a handler for GET method.
* @param handler Handler for GET method.
*/
get(handler: Handler) {
this.handlers.set("GET", handler);
}
/**
* Register a handler for POST method.
* @param handler Handler for POST method.
*/
post(handler: Handler) {
this.handlers.set("POST", handler);
}
/**
* Register a handler for PUT method.
* @param handler Handler for PUT method.
*/
put(handler: Handler) {
this.handlers.set("PUT", handler);
}
/**
* Register a handler for PATCH method.
* @param handler Handler for DELETE method.
*/
delete(handler: Handler) {
this.handlers.set("DELETE", handler);
}
/**
* Serves HTTP requests.
* @param options Options for `serve`.
*/
serve(options?: ServeInit) {
serve(
async (req: Request, connInfo: ConnInfo) => {
const method = req.method.toUpperCase();
const handler = this.handlers.get(method) || defaultHandler;
return await handler(req, connInfo);
},
options,
);
}
}
export { App };