ArrowHead ArrowHead - 1 year ago 152
Node.js Question

How to dynamically connect to databases in Sails.js

I am rebuilding a legacy PHP application using nodejs and I choose sailsjs after about a week of exploration. Everything was fine until I realised that in sails you only have access to session variables in your controllers. Thus, I cannot make dynamic connections with the model.

The legacy up uses PHP session global variables to connect to different postgresql databases after authentication and I can't seem to find a work around on the web. I have seen similar questions on sails around the web. Any node/sails/database geeks around?

I am thinking of using sails for authentication since it already works and using expressjs to implement services that my sails app would then call by sending db connection params in some form of microservice architecture.

Currenttly running sails on localhost:1337 and my express on localhost:3000. Is this a good way to go about?

Answer Source

I am answering my own question here, similar questions have been asked here and none of the answers provided seems to work. Instead of using waterline in my models, I have used successfully the pg module,

$ npm install pg --save
var pg = require('pg');

in this way, I can dynamically pass the connection string from my controller to my models and disregard the waterline ORM.

I created a sails service to get and set the database connection string for each session.

Then for each query I pass the connection string stored in session around :

var sessionConnection = ConnectionsService.getSessionConnection(req,res);

  pg.connect(sessionConnection, function(err, client, done) {
     // do connection stuff and queries here


Hope this helps others