Skip to content

Instantly share code, notes, and snippets.

@luislobo
Created June 13, 2019 23:21
Show Gist options
  • Save luislobo/e267b8c607327cc609b9b84fecb103dc to your computer and use it in GitHub Desktop.
Save luislobo/e267b8c607327cc609b9b84fecb103dc to your computer and use it in GitHub Desktop.
How to handle MongoDB reconnection on Sails

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

@luislobo
Copy link
Author

FInal note: use a fork of sails-mongo that works with atlas: "sails-mongo": "github:PetroCloud/sails-mongo#0-13",

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment