-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.ts
86 lines (74 loc) · 2.43 KB
/
app.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
import dotenv from 'dotenv';
dotenv.config({path: `${__dirname}/../.env`});
import express from 'express';
import routerRoot from './routes/root.route';
import config from './configurations';
// setup api clients
import {logger} from './utilities/logger';
import {Server} from 'http';
import helmet from 'helmet';
// import cors from 'cors';
import {destroyClients, setupClients} from './clients';
/**
* Prepare the Express HTTP server
* @returns A promise to Server which resolves once it starts listening.
*/
export async function launchServer(): Promise<Server> {
logger.log('===== CONFIGURATION =====\n', config);
// logger.log('======= CONSTANTS =======\n', constants);
const app = express();
// setup middlewares
// app.use(cors()); // @TODO add cors options for allowed origins
app.use(helmet());
app.use(express.urlencoded({extended: true}));
app.use(express.json());
// setup routers
app.use(routerRoot);
const setupSuccess = await setupClients();
// listen
return await new Promise((resolve, reject) => {
if (setupSuccess) {
// healthchecks pass, start listening
const server = app.listen(config.Server.Port, () => {
logger.log('========= LIVE! =========');
logger.log('Listening on port:', config.Server.Port);
resolve(server);
});
} else {
reject('Healthchecks failed!');
}
});
}
/**
* Kills the server gracefully. Optionally exits the process, which you should NOT if you are testing.
* @param server the HTTP server to close
* @param exitProcess do process.exit after closing?
*/
export async function killServer(server: Server, exitProcess = false) {
logger.log('\n\nKilling server.');
await destroyClients();
server.close(err => {
if (err) {
logger.log('Error during termination.', err);
// eslint-disable-next-line no-process-exit
exitProcess && process.exit(1);
} else {
logger.log('Gracefully terminated. 💐');
// eslint-disable-next-line no-process-exit
exitProcess && process.exit(0);
}
});
}
if (require.main === module) {
launchServer()
.then(server => {
// signal listeners
process.on('SIGTERM', () => killServer(server, true));
process.on('SIGINT', () => killServer(server, true));
})
.catch(err => {
logger.log('Could not launch server:', err);
// eslint-disable-next-line no-process-exit
destroyClients().then(() => process.exit(1));
});
}