-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver.ts
85 lines (68 loc) · 2.47 KB
/
webserver.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
import { injectable, inject } from "inversify";
import * as express from "express";
import bodyParser = require("body-parser");
import * as compression from "compression";
import { log } from "@swingletree-oss/harness";
import { ConfigurationService, ScottyConfig } from "./configuration";
import { Request, Response, NextFunction } from "express-serve-static-core";
@injectable()
export class WebServer {
private app: express.Express;
private port: number;
constructor(
@inject(ConfigurationService) configService: ConfigurationService
) {
this.app = express();
this.port = configService.getNumber(ScottyConfig.Scotty.PORT);
this.initialize();
}
private initialize() {
log.info("initializing server...");
const maxBodySize = process.env["MAX_BODY_SIZE"] || "1mb";
log.info("setting max body-size to %s", maxBodySize);
// express configuration
this.app.set("port", this.port);
this.app.use(compression());
this.app.use(bodyParser.json({
limit: maxBodySize
}));
this.app.use(bodyParser.urlencoded({
limit: maxBodySize,
extended: true
}));
// set common headers
this.app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
res.header("X-Frame-Options", "DENY");
res.header("X-XSS-Protection", "1");
res.header("X-Content-Type-Options", "nosniff");
next();
});
// disable server reveal
this.app.disable("x-powered-by");
// set rendering engine
this.app.set("view engine", "pug");
// health endpoint
this.app.get("/health", (request: express.Request, response: express.Response) => {
response.sendStatus(200);
});
// error handling
this.app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
// only provide error details in development mode
const visibleError = req.app.get("env") === "development" ? err : {};
res.status(err.status || 500);
res.send(visibleError);
});
// kickstart everything
this.app.listen(this.app.get("port"), () => {
log.info("listening on http://localhost:%d in %s mode", this.app.get("port"), this.app.get("env"));
});
}
public addRouter(path: string, router: express.Router) {
log.debug("adding http endpoint %s", path);
this.app.use(path, router);
}
public setLocale(key: string, data: any) {
log.debug("adding locals entry for key %s", key);
this.app.locals[key] = data;
}
}