Skip to content

Commit

Permalink
Add health check + error handling for mongoose connect
Browse files Browse the repository at this point in the history
  • Loading branch information
sodik82 committed Dec 5, 2021
1 parent 4b15d39 commit 8698aec
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 6 deletions.
4 changes: 4 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "es5"
}
31 changes: 25 additions & 6 deletions server/db/connect.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,32 @@ const mongoose = require('mongoose');
mongoose.set('debug', false);
mongoose.Promise = global.Promise;

const MONGO_URL = process.env.MONGO_URL;
mongoose.connect(MONGO_URL || 'mongodb://localhost/data', {
useMongoClient: true
});
const MONGO_URL = process.env.MONGO_URL || 'mongodb://localhost/data';
const MONGO_OPT = {
useMongoClient: true,
};

async function connectMongo() {
try {
await mongoose.connect(MONGO_URL, MONGO_OPT);
} catch (err) {
console.log('Connect to database failed -> exiting');
// k8s can restart the pod
process.exit(-1);
}
}
connectMongo().then(() => console.log('Database connected'));

const db = mongoose.connection;

db.on('error', (err) => console.log('Error connecting to database: ', err));
db.on('disconnected', (err) => console.log('Disconnected from the database: ', err));
db.on('close', (err) => console.log('Closed the connection to the database: ', err));
db.on('disconnected', async (err) => {
console.log('Disconnected from the database -> exiting: ', err);
// mongo/mongoose are stupid - can't retry normally.
// when I try to reconnect here, it fails with `MongooseError [OverwriteModelError]: Cannot overwrite `Place` model once compiled.`
// so it might be better to let k8s to restart the pod
process.exit(-2);
});
db.on('close', (err) =>
console.log('Closed the connection to the database: ', err)
);
29 changes: 29 additions & 0 deletions server/health-check/health-check.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const { getUserByEmail } = require('../service/userService');

const checkMongo = async () => {
await getUserByEmail('[email protected]');
};

const checks = [checkMongo];

const healthCheck = async (req, res) => {
let ok = true;
const response = {};
const performCheck = async (fn) => {
try {
await fn();
response[fn.name] = 'ok';
} catch (err) {
response[fn.name] = `${err}`;
ok = false;
}
};
await Promise.all(checks.map((fn) => performCheck(fn)));
return res.status(ok ? 200 : 500).json(response);
};

const setupHealthCheck = (app) => {
app.use('/health-check', healthCheck);
};

module.exports = { setupHealthCheck };
2 changes: 2 additions & 0 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ const cors = require('cors');
const { setupAttendenceApi } = require('./api/attendenceApi');

const exportMiddleware = require('./export/exportMiddleware');
const { setupHealthCheck } = require('./health-check/health-check');

const argv = require('minimist')(process.argv.slice(2));

Expand Down Expand Up @@ -44,6 +45,7 @@ app.use('/graphql', graphqlHTTP((req) => ({
})));

setupAttendenceApi(app);
setupHealthCheck(app);

app.use('/export/*', bodyParser.json());
app.post('/export/*', exportMiddleware);
Expand Down

0 comments on commit 8698aec

Please sign in to comment.