-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
98 lines (84 loc) · 2.7 KB
/
server.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
91
92
93
94
95
96
97
98
import { Hono } from "hono";
import { secureHeaders } from "hono/secure-headers";
import { cors } from "hono/cors";
import { prettyJSON } from "hono/pretty-json";
import { logger as honoLogger } from "hono/logger";
import { swaggerUI } from "@hono/swagger-ui";
import { configs } from "@config";
import { StatusCode } from "@constants";
import swaggerDefinitions from "@docs/swagger.json";
import logger from "./logger";
/**
* A server class that configures HTTP server.
*/
class Server {
public app: Hono;
private static instance: Server;
/**
* Only accepts routes which are derived from BaseRoute class
* @param routes indicates that array of route classes
*/
private constructor(routes: IBaseRoute[]) {
this.app = new Hono().basePath(configs.basePath);
this.initializeMiddlewares();
this.initializeRoutes(routes);
}
/**
*
* @param routes indicates that array of route classes
* @returns server class
*/
public static getInstance(routes: IBaseRoute[]): Server {
if (!Server.instance) {
Server.instance = new Server(routes);
}
return Server.instance;
}
/**
* Initializes global middlewares
*/
private initializeMiddlewares() {
this.app.use("*", prettyJSON());
this.app.use("*", cors());
this.app.use(
"*",
secureHeaders({
xPermittedCrossDomainPolicies: "none",
xFrameOptions: "deny",
xContentTypeOptions: "nosniff",
strictTransportSecurity: "max-age=63072000; includeSubDomains; preload",
xXssProtection: "1; mode=block"
})
);
this.app.use(
"*",
honoLogger((message: string, ...rest: string[]) => {
logger.info(`${message} ${rest.toString()}`);
})
);
this.app.get("/doc", (c) => {
return c.json(swaggerDefinitions);
});
this.app.get(
"/ui",
swaggerUI({ url: configs.basePath ? configs.basePath + "/doc" : "/doc" })
);
}
/**
* Initializes routes
* @param routes indicates that routes which are derived from BaseRoute class
*/
private initializeRoutes(routes: IBaseRoute[]) {
routes.forEach((route) => {
this.app.route(route.basePath, route.router);
});
this.app.notFound((c) => {
return c.text("Not found!", StatusCode.NotFound);
});
this.app.onError((err, c) => {
console.error(`${err}`);
return c.text("An error occured!", StatusCode.InternalServerError);
});
}
}
export default Server;