我需要根据请求源切换loopback datasource中的数据库
例如。如果我从 xyz.domain.com
发出请求,我需要为数据源选择 xyz
数据库(我们在前端使用通配符子域,因此会有多个这样的子域)。
我尝试构建从每个请求来源提取子域并为数据源设置数据库的中间件。现在的问题是在几个并发请求之后,环回服务器因“太多连接”错误而中断(可能是因为它在每个请求上都创建了新的连接线程)
(我正在为数据源使用 my-sql 连接器)
下面是我的中间件代码
'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();
};
};
实现此目的的其他方法也很有帮助。
最佳答案
app.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);
}
});
}
...
关于javascript - Loopbackjs:根据请求来源切换数据源中的数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41888222/