First, create a custom configuration with this structure:
dbStatus: {
timeoutIncrement: 5 * 1000,
initialTimeout: 5 * 1000,
maxTimeout: 60 * 1000,
dbOnline: true
}
Have a helper/service file (for example /api/services/UtilsService.js
) with:
let checkDbTimeout = sails.config.custom.dbStatus.initialTimeout;
dbStatus() {
sails.log.silly('checking if db is online', checkDbTimeout);
Promise.try(() =>
// wrap in a promise, since when we reload the orm and it cannot connect,
// all models are gone and User.count does not exist
User.count()
)
.then((count) => {
// if we hit here, then, db is online
sails.log.silly('db is online', count);
sails.config.custom.dbStatus.dbOnline = true;
checkDbTimeout = sails.config.custom.dbStatus.initialTimeout;
setTimeout(UtilsService.dbStatus, checkDbTimeout);
})
.catch(() => {
// if we hit here, then, db is offline
sails.log.warn('db is offline');
sails.config.custom.dbStatus.dbOnline = false;
sails.log.warn('reloading orm', checkDbTimeout);
sails.hooks.orm.reload((err) => {
if (err) {
checkDbTimeout += sails.config.custom.dbStatus.timeoutIncrement;
if (checkDbTimeout > sails.config.custom.dbStatus.maxTimeout) {
checkDbTimeout = sails.config.custom.dbStatus.maxTimeout;
}
} else {
sails.config.custom.dbStatus.dbOnline = true;
checkDbTimeout = sails.config.custom.dbStatus.initialTimeout;
}
setTimeout(UtilsService.dbStatus, checkDbTimeout);
});
});
},
Finally, in your config/bootstrap.js
file, call UtilsService.dbStatus();
It's kind of cumbersome, but it works
FInal note: use a fork of sails-mongo that works with atlas:
"sails-mongo": "github:PetroCloud/sails-mongo#0-13",