I am trying to create a multi-tenant app (saas), where each client has its own database.
My situation is:
I created a middleware that would determine who the client is based on a subdomain, then retrieve the client's database connection info from a general database. I don't know how to establish a connection object for this client so as to be able to use in my controllers. And should I do this in the middleware or in a controller? And if it's in the model, how do i pass the connection string and parameters (I could use session, but I don't know how to access session from within model).
How do i do the following?
- Organisation: where do I create the db connection for client dynamically?
- Inject/pass connection parameters to controller or model (where connection definition is made)
- After dynamic connection has been made, how do i access it globally for that client?
This is an example of my middleware, and i would like to create a mongoose connection which i would like to make dynamic (pass in client's connection info):
function clientlistener() {
return function (req, res, next) {
console.dir('look at my sub domain ' + req.subdomains[0]);
// console.log(req.session.Client.name);
if (req.session.Client && req.session.Client.name === req.subdomains[0]) {
var options = session.Client.options;
var url = session.Client.url
var conn = mongoose.createConnection(url, options);
next();
}
}
}
How do I access this connection object from inside the controller? Or from the model?
Thank you.