Skip to content

Commit

Permalink
feat: add healthcheck
Browse files Browse the repository at this point in the history
  • Loading branch information
guillermocorrea committed Dec 21, 2020
1 parent 9076769 commit 89d8d80
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
31 changes: 31 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"typescript": "^4.1.3"
},
"dependencies": {
"@godaddy/terminus": "^4.5.0",
"bunyan": "^1.8.14",
"bunyan-express-serializer": "^1.0.0",
"class-transformer": "^0.3.1",
Expand Down
23 changes: 22 additions & 1 deletion src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import usersRoutes from './routes/users.routes';
import './database';
import './di.container';
import { environment } from './environment';
import { createTerminus } from '@godaddy/terminus';
import mongoose from 'mongoose';
import http from 'http';

export class Server {
private app: express.Application;
Expand All @@ -22,6 +25,18 @@ export class Server {
this.routes();
}

private async onSignal() {
console.log('server is starting cleanup');
await mongoose.disconnect();
console.log('MongoDB Disconnected!');
}

private async onHealthCheck() {
// checks if the system is healthy, like the db connection is live
// resolves, if health, rejects if not
return mongoose.connection.readyState === 1;
}

private async config() {
// Settings
this.app.set('port', process.env.PORT || 3000);
Expand Down Expand Up @@ -60,7 +75,13 @@ export class Server {
}

async start() {
this.app.listen(this.app.get('port'), () => {
const server = http.createServer(this.app);
createTerminus(server, {
signal: 'SIGINT',
healthChecks: { '/healthcheck': this.onHealthCheck },
onSignal: this.onSignal,
});
server.listen(this.app.get('port'), () => {
console.log('Listening on port', this.app.get('port'));
});
}
Expand Down

0 comments on commit 89d8d80

Please sign in to comment.