Skip to content

Commit

Permalink
feat(lib): add graceful shutdown, prevention for docker ✨
Browse files Browse the repository at this point in the history
  • Loading branch information
PierreBrisorgueil committed Apr 27, 2020
1 parent 465fd8b commit eaa6a8e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
30 changes: 26 additions & 4 deletions lib/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
* Module dependencies.
*/
const chalk = require('chalk');
const http = require('http');
const https = require('https');
const nodeHttp = require('http');
const nodeHttps = require('https');

const config = require('../config');
const mongooseService = require('./services/mongoose');
Expand Down Expand Up @@ -104,6 +104,7 @@ exports.start = async () => {
let db;
let orm;
let app;
let http;

try {
({ db, orm, app } = await bootstrap());
Expand All @@ -112,15 +113,36 @@ exports.start = async () => {
}

try {
if (config.secure && config.secure.credentials) await https.createServer(config.secure.credentials, app).listen(config.port, config.host);
else await http.createServer(app).listen(config.port, config.host);
if (config.secure && config.secure.credentials) http = await nodeHttps.createServer(config.secure.credentials, app).listen(config.port, config.host);
else http = await nodeHttp.createServer(app).listen(config.port, config.host);
logConfiguration();
return {
db,
orm,
app,
http,
};
} catch (e) {
throw new Error(e);
}
};

// Shut down the server
exports.shutdown = async (server) => {
try {
server.then(async (value) => {
await mongooseService.disconnect();
// add sequelize
value.http.close((err) => {
console.info(chalk.yellow('Server closed'));
if (err) {
console.info(chalk.red('Error on server close.', err));
process.exitCode = 1;
}
process.exit();
});
});
} catch (e) {
throw new Error(e);
}
};
13 changes: 12 additions & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,20 @@
* Module dependencies.
*/

const chalk = require('chalk');
const app = require('./lib/app');

app.start().catch((e) => {
const server = app.start().catch((e) => {
console.log(`server failed: ${e.message}`);
throw (e);
});

process.on('SIGINT', () => {
console.info(chalk.blue(' SIGINT Graceful shutdown ', new Date().toISOString()));
app.shutdown(server);
});

process.on('SIGTERM', () => {
console.info(chalk.blue(' SIGTERM Graceful shutdown ', new Date().toISOString()));
app.shutdown(server);
});

0 comments on commit eaa6a8e

Please sign in to comment.