/
bootstrap.ts
62 lines (46 loc) · 1.8 KB
/
bootstrap.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
import { Container, ContainerModule } from "inversify";
import * as express from "express";
import { InversifyExpressServer } from "inversify-express-utils";
import * as bodyParser from "body-parser";
import * as helmet from "helmet";
import { reqMiddleware, exceptionLoggerMiddleware } from "./middleware";
import { DbClient, getDatabaseClient } from "../data_access/db_client";
import { TYPES } from "../../domain/constants/types";
export async function bootstrap(
container: Container,
appPort: number,
dbHost: string,
dbName: string,
...modules: ContainerModule[]
) {
if (container.isBound(TYPES.App) === false) {
const dbClient = await getDatabaseClient(dbHost, dbName);
container.bind<DbClient>(TYPES.DbClient).toConstantValue(dbClient);
container.load(...modules);
// Configure express server
const server = new InversifyExpressServer(container);
server.setConfig((app) => {
// Disable default cache
app.set("etag", false);
// Configure requests body parsing
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Adds some decurity defaults
app.use(helmet());
// Log all requets that hit the server
app.use(reqMiddleware);
});
server.setErrorConfig((app) => {
// Catch and log all exceptions
app.use(exceptionLoggerMiddleware);
});
const app = server.build();
// Run express server
console.log(`Application listening on port ${appPort}...`);
app.listen(appPort);
container.bind<express.Application>(TYPES.App).toConstantValue(app);
return app;
} else {
return container.get<express.Application>(TYPES.App);
}
}