1 | // @see https://stackoverflow.com/questions/9299331/what-is-the-best-practice-to-gracefully-shutdown-a-node-js-program-from-an-exter |
||
2 | 'use strict' |
||
3 | |||
4 | import mongoose from 'mongoose' |
||
5 | import chalk from 'chalk' |
||
6 | import logger from 'winston' |
||
7 | import assert from 'assert-plus' |
||
8 | |||
9 | // pluging in own promise library instead: http://mongoosejs.com/docs/promises.html |
||
10 | mongoose.Promise = require('bluebird') |
||
11 | |||
12 | let databaseResolve = () => {} |
||
13 | let databaseReject = () => {} |
||
14 | export const databaseValidate = new Promise((resolve, reject) => { |
||
15 | databaseResolve = resolve |
||
16 | databaseReject = reject |
||
17 | }) |
||
18 | |||
19 | const isTest = process.env.NODE_ENV === 'test' |
||
20 | function notify (done) { |
||
21 | if (!isTest && typeof done === 'function') { |
||
22 | done() |
||
23 | } |
||
24 | } |
||
25 | |||
26 | export default function (db) { |
||
27 | assert.ok(db, 'mongo_uri not found') |
||
28 | mongoose.connect(db) |
||
29 | |||
30 | mongoose.connection.on('connected', () => { |
||
31 | notify(() => logger.info('[database]', `Mongoose connected on ${chalk.cyan(db)}`)) |
||
32 | databaseResolve() |
||
33 | }) |
||
34 | mongoose.connection.on('error', (err) => { |
||
35 | databaseReject(err) |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
36 | }) |
||
37 | mongoose.connection.on('disconnected', () => { |
||
38 | notify(() => logger.info('[database]', chalk.yellow('Mongoose disconnected'))) |
||
39 | }) |
||
40 | // CAPTURE APP TERMINATION / RESTART EVENTS |
||
41 | // To be called when process is restarted or terminated |
||
42 | const gracefulShutdown = (msg, callback) => { |
||
43 | mongoose.connection.close(() => { |
||
44 | notify(() => logger.info('[database]', chalk.yellow(`Mongoose disconnected through ${chalk.bold(msg)}`))) |
||
45 | callback() |
||
46 | }) |
||
47 | } |
||
48 | // For nodemon restarts |
||
49 | process.once('SIGUSR2', () => { |
||
50 | gracefulShutdown('nodemon restart', () => { |
||
51 | process.kill(process.pid, 'SIGUSR2') |
||
52 | }) |
||
53 | }) |
||
54 | // For app termination |
||
55 | process.on('SIGINT', () => { |
||
56 | gracefulShutdown('app termination', () => { |
||
57 | process.exit(0) |
||
58 | }) |
||
59 | }) |
||
60 | // For Heroku app termination |
||
61 | process.on('SIGTERM', () => { |
||
62 | gracefulShutdown('Heroku app termination', () => { |
||
63 | process.exit(0) |
||
64 | }) |
||
65 | }) |
||
66 | } |
||
67 |