Skip to content

Commit

Permalink
correct and simplify shutdown hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
Qix- authored and leo committed Apr 24, 2018
1 parent b2d35ee commit 95ffc80
Showing 1 changed file with 19 additions and 8 deletions.
27 changes: 19 additions & 8 deletions bin/micro.js
Expand Up @@ -179,6 +179,21 @@ if (!existsSync(file)) {
process.exit(1);
}

function registerShutdown(fn) {
let run = false;

const wrapper = () => {
if (!run) {
run = true;
fn();
}
};

process.on('SIGINT', wrapper);
process.on('SIGTERM', wrapper);
process.on('exit', wrapper);
}

function startEndpoint(module, endpoint) {
const server = serve(module);

Expand All @@ -190,14 +205,7 @@ function startEndpoint(module, endpoint) {
server.listen(...endpoint, () => {
const details = server.address();

const shutdown = () => {
console.log('micro: Gracefully shutting down. Please wait...');
server.close();
};

process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
process.on('exit', shutdown);
registerShutdown(() => server.close());

// `micro` is designed to run only in production, so
// this message is perfectly for prod
Expand All @@ -213,9 +221,12 @@ function startEndpoint(module, endpoint) {

async function start() {
const loadedModule = await handle(file);

for (const endpoint of args['--listen']) {
startEndpoint(loadedModule, endpoint);
}

registerShutdown(() => console.log('micro: Gracefully shutting down. Please wait...'));
}

start();

0 comments on commit 95ffc80

Please sign in to comment.