Skip to content

Commit

Permalink
Add Exit Scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
smrsan committed Oct 31, 2021
1 parent a5763c3 commit d4948bf
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/exit.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import chalk from "chalk";

import { dbClient } from "./db";

process.stdin.resume(); //so the program will not close instantly

function exitHandler(
options: { cleanup?: boolean; exit?: boolean },
exitCode?: number
) {
if (options.cleanup) {
console.log(chalk.blueBright("DB Closed Successfully"));
dbClient.close(true).catch(console.error);
}
if (exitCode || exitCode === 0) console.log("Exit Code:", exitCode);
if (options.exit) process.exit();
}

//do something when app is closing
process.on("exit", exitHandler.bind(null, { cleanup: true }));

//catches ctrl+c event
process.on("SIGINT", exitHandler.bind(null, { exit: true }));

// catches "kill pid" (for example: nodemon restart)
process.on("SIGUSR1", exitHandler.bind(null, { exit: true }));
process.on("SIGUSR2", exitHandler.bind(null, { exit: true }));

//catches uncaught exceptions
process.on("uncaughtException", exitHandler.bind(null, { exit: true }));
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
import "./db";
import "./exit";

0 comments on commit d4948bf

Please sign in to comment.