-
Notifications
You must be signed in to change notification settings - Fork 8
/
application.ts
61 lines (52 loc) · 1.4 KB
/
application.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
import { serve } from "https://deno.land/std@v0.58.0/http/server.ts";
import { Context } from "./context.ts";
import { Router } from "./router/router.ts";
import { Middleware } from "./middlewares/middleware.ts";
type ServerConfig = {
port?: number;
log?: boolean;
};
export class Application {
private log: boolean;
private port: number = 3000;
private server: any;
private router: any;
private middlewares: Middleware[] = [];
constructor(serverConfig?: ServerConfig) {
this.port = serverConfig?.port || 80;
this.log = serverConfig?.log ? true : false;
this.router = new Router();
}
start(port: number = this.port) {
this.server = serve({ port });
if (this.log) console.log(`Server Listening on Port ${port}`);
this.listen();
}
use(...middlewares: Middleware[]) {
this.middlewares.push(...middlewares);
}
get(...params: any) {
this.router.get(...params);
return this;
}
post(...params: any) {
this.router.post(...params);
return this;
}
put(...params: any) {
this.router.put(...params);
return this;
}
delete(...params: any) {
this.router.delete(...params);
return this;
}
private async listen() {
for await (const request of this.server) {
for (const middleware of this.middlewares) {
await middleware(new Context(request));
}
this.router.handleRequest(request, this.log);
}
}
}