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);
let dataSource = new DataSource({
'host': 'localhost',
'port': 3306,
'database': subdomain ? subdomain[1] || 'default' : 'default',
'user': 'user',
'password': 'user',
'name': 'mysqlDS',
'connector': 'mysql'
});
let models = app.models();
models.forEach(function(model) {
if (model.modelName !== 'Email') {
model.attachTo(dataSource);
}
});
app.dataSource("mysqlDS", dataSource);
}
next();
};
};
Run codeHide resultOther approaches to achieve this may also be useful.
source
share