Home > Software design >  Route all the requests to specific database express node js
Route all the requests to specific database express node js

Time:05-18

I am working on a saas app (separate db for each client) backend uisng node js, express and mysql and sequelize orm. Url is : http://example.com/customer/api Here customers count can be in 1000's Now i need to get that customer name and connect to there database and then route all the requests to that database. When ever a request comes this has to be done. // first connect to the customer db Then app.use('/api', routes) routes here has all the routes on the application. What is to be done to handle this? I need a way to connect to that customer db as and when requests arrive and then process requests on that customer database.

CodePudding user response:

How do you get the corresponding database? a middleware could route between the different databases for example user "x" makes a request. The middleware searches for the corresponding database for user x and puts the connection String for the database in the req. The handler for the request than gets the conn String and connects to the corresponding database. The connection could than be cached with for example node-cache and than retrieved later on when the customer needs another request.

Edit:

some code

var express = require('express');
var app = express();
    
var getDb = function (req, res, next) {
  req.body.username //get for example the username
  //search for the corresponding connection string in the database
  //then add it to the request
  req.databaseString = connString //connString --the connection 
  // String you got earlier
  next();
};
    
app.use(getDb);
    
app.get('/makeSomething', function (req, res) {
  //connect to db with req.databaseString
  //do what you wanna do
    
  res.send('done');
});
    
app.listen(3000);

Adding to your comment above. "My question is does the routes here know which DB to connect?" the routes know this when they look in the req and look for a connection string. With the connection String they know which DB to use.

  • Related