jlanza
jlanza

Reputation: 1258

Create databases connection on startup - sails.js

I know you can use Waterline and the models approach, but the issue is that I have to access more than one database to generate a response. Besides the models approach makes it difficult to think on a solution due to the fact that the data is joined and infered from different tables under the different databases.

Therefore, I would like to know how can I open a DB connection using the mysql or mysql2 native driver and reuse it all over the app. Where is the most suitable place, a hook, etc.? How can I close them when the app goes down?

TA

Upvotes: 0

Views: 329

Answers (1)

Gergo
Gergo

Reputation: 2290

A custom hook will be the best for you. For Redis, I created one like this:

api/hooks/redis/index.js

var redisModule = require('redis');

module.exports = function connectToRedis(sails) {

  return {
    connectToRedis: function (callback) {
      var hook = this;
      var config = sails.config.connections.redis;
      var redisClient = redisModule.createClient(config.port, config.host);

      hook.initAdapters();

      redisClient.on('connect', function () {
        sails.log.verbose('Connection to redis was succesfull!');

        // select db
        redisClient.select(config.db, function (err) {
          if (err) {
            return callback(err);
          }

          sails.adapters.redis = redisClient;

          callback();
        });
      });
      redisClient.on('error', function (error) {
        sails.log.error(error);
        callback();
      });
    },

    initAdapters: function () {
      if (sails.adapters === undefined) {
        sails.adapters = {};
      }
    },

    // Run automatically when the hook initializes
    initialize: function (cb) {
      var hook = this;
      hook.connectToRedis(function() {
        cb();
      });
    },
  };
};

Upvotes: 1

Related Questions