0

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

1 Answer 1

1

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();
      });
    },
  };
};
Sign up to request clarification or add additional context in comments.

2 Comments

This is quite inline with what I had in mind. I don't like using waterline and prefer using my own data connection ;)
I don't like waterline neither, thats why I wrote a custom solution for this. Also I created a Sequelize hook module: https://github.com/festo/sails-hook-sequelize

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.