-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.js
66 lines (60 loc) · 1.61 KB
/
server.js
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
/**
* Configures and starts the server
*/
const mongoose = require('mongoose');
const { dbUrl, port } = require('./config')();
require('newrelic');
const redis = require('./config/redis');
const app = require('./app');
const { logger } = require('./utils');
// Connecting to MongoDB
mongoose
.connect(dbUrl, {
useNewUrlParser: true,
})
.then(() => {
logger.log('info', 'Successfully connected to MongoDB');
})
.catch((error) => {
logger.log('error', 'Failed to connect to mongo database', {
error,
});
});
const server = app.listen(port, () => {
logger.log('info', `Server running on PORT ${port} in ${process.env.NODE_ENV} mode`);
});
// Graceful shutdown
function gracefulShutdown() {
// Prevent the server from receiving anymore incoming requests
server.close((error) => {
if (error) {
process.exit(error ? 1 : 0);
}
logger.log('info', 'Shutting down server');
// Disconnect from MongoDB
mongoose
.disconnect()
.then(() => {
logger.log('info', 'Successfully disconnected from database');
// Disconnect from redis-server
redis
.quitAsync()
.then(() => {
logger.log('info', 'Successfully disconnected from redis');
process.exit(0);
})
.catch((err) => {
logger.log('error', 'Failed to close redis connections', err);
process.exit(1);
});
})
.catch((err) => process.exit(err ? 1 : 0));
});
}
process.on('SIGINT', () => {
gracefulShutdown();
});
process.on('SIGTERM', () => {
gracefulShutdown();
});
module.exports = server;