Loopbackjs: DB switch in data source based on query source

I need to switch the database to a loopback data source based on the request source

eg. If I make a request from , I need to select a database for the data source (we use a wildcard subdomain on the interface, so there will be several such subdomains). xyz.domain.com xyz

I tried to create middleware that extracts a subdomain from each query source and sets up a database for the data source. Now the problem is that after several simultaneous requests, the loopback server is interrupted with the error "too many connections" (maybe because it creates a new connection flow for each request)

(I use the my-sql connector for the data source)

Below is my middleware code

'use strict';

const DataSource = require('loopback-datasource-juggler').DataSource;
const app = require('../../server/server.js');
const getSubdomain = require('../middlewares/getSubdomain.js');

module.exports = function() {
  return function datasourceSelector(req, res, next) {
    if (req.path !== '/api/check-realm') {
      let subdomain = getSubdomain(req); // this will get me subdomain from request origin

      let dataSource = new DataSource({
        'host': 'localhost',
        'port': 3306,
        'database': subdomain ? subdomain[1] || 'default' : 'default',
        'user': 'user',
        'password': 'user',
        'name': 'mysqlDS',
        'connector': 'mysql'
      }); // This creates new datasource on every request with appropriate database

      let models = app.models();

      models.forEach(function(model) {
        if (model.modelName !== 'Email') {
          model.attachTo(dataSource);
        }
      }); // here I am attaching all models to the newly created datasource.

      app.dataSource("mysqlDS", dataSource);

    }
    next();
  };
};
Run codeHide result

Other approaches to achieve this may also be useful.

+4
source share
1 answer

app.datasources contains all the data sources that you define in the application.

For instance:

//datasources.json

{
  "memo": {
    "name": "memo",
    "connector": "memory"
  },
  "admin": {
    "host": "localhost",
    "port": 27017,
    "url": "",
    "database": "test_db",
    "password": "",
    "name": "admin",
    "user": "",
    "connector": "mongodb"
  }

:

...
if (subdomain === 'admin'){
   models.forEach(function(model) {
        if (model.modelName !== 'Email') {
          model.attachTo(app.datasources.admin);
        }
      });
}
...
0

Source: https://habr.com/ru/post/1667945/


All Articles