-
Notifications
You must be signed in to change notification settings - Fork 0
/
Blazin.ts
68 lines (60 loc) · 2.39 KB
/
Blazin.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
import { serve, serveTLS } from "https://deno.land/std/http/server.ts";
import { Router } from "./core/Router.ts"
import { Response } from "./core/Response.ts";
import { Logger } from "./core/Logger.ts"
export class Blazin {
private port: number;
private server: any;
public router: Router;
constructor(prt: number) {
this.port = prt;
this.server = null
this.router = new Router(this.server);
}
private async handleRequests(): Promise<void> {
try {
for await (const req of this.server) {
const res = new Response(req);
const conn = res.request.conn.remoteAddr
const route = this.router.getRoutes().find(route => route.getUri() == res.request.url && route.getHttpMethod() == res.request.method)
// log request in server console
Logger.info(`Path: ${res.request.url} From: ${conn.transport}://${conn.hostname}:${conn.port}`)
// fetch the favicon
if(res.request.url === "/favicon.ico") {
this.router.favicon();
// process the request if the route exists
} else if (route) {
// execute the middlewares
for (const middleware of this.router.middlewares) {
middleware.function(res.request)
}
route.function(res)
// send not found if route does not exist
} else {
this.router.notfound(res)
}
}
} catch (e) {
console.error(e);
}
}
public start(scheme: string = "http", options: any = {}): void {
this.server = (scheme != "https") ? serve({port: this.port}) : serveTLS(options);
this.handleRequests();
Logger.info(`Blazin fast server started on ${scheme}://${this.server.listener.addr.hostname}:${this.port}`);
}
public use(object: any): boolean {
switch(object.constructor) {
case Router:
this.router.mergeRouter(object);
Logger.info("Successfully merged router to app router");
return true;
default:
Logger.warn(`Could not find implementation of .use() for object type of ${typeof object}`);
return false;
}
}
};
export {
Router
};