续集:根据请求在运行时间上连接到数据库



我正在使用node.js应用程序,我需要在其中连接到一个以上的数据库。数据库之一是中央数据库,其中包含所有人共有的信息。然后在国家级数据库中,根据国家/地区存储数据。

我在应用程序中使用semelize orm。
数据库是postgresql。
框架是明确的。

问题是我想根据请求决定使用哪个数据库,并应自动连接到适当的数据库。我已经看到了这个问题,但没有发现有帮助。

我也在另一个论坛上检查了一下。

您需要创建与每个数据库相对应的对象,并且在每个对象上,您需要实例化续集。此外,对于每个续集实例,您需要导入模型(屁股所有这些数据库都具有完全相同的表和模型表示)。

import Sequelize from 'sequelize';
let connectionsArray = [
    'postgres://user:pass@example.com:5432/country1',
    'postgres://user:pass@example.com:5432/country2',
    'postgres://user:pass@example.com:5432/country3',
];
let country1DB, country2DB, country3DB;
country1DB = country2DB = country3DB = {};
country1DB.Sequelize = country2DB.Sequelize = country3DB.Sequelize = Sequelize;
country1DB.sequelize = new Sequelize(connectionsArray[0]);
country2DB.sequelize = new Sequelize(connectionsArray[1]);
country3DB.sequelize = new Sequelize(connectionsArray[2]);
// here you need to access the models path, maybe with fs module
// iterate over every model and import it into every country sequelize instance
// let's assume that models' paths are in simple array
models.forEach(modelFile => {
    let model1DB = country1DB.sequelize.import(modelFile);
    let model2DB = country2DB.sequelize.import(modelFile);
    let model3DB = country3DB.sequelize.import(modelFile);
    country1DB[model1DB.name] = model1DB;
    country2DB[model2DB.name] = model2DB;
    country3DB[model3DB.name] = model3DB;
});
// now every country?DB object has it's own sequelize instance and all model definitions inside
export {
    country1DB,
    country2DB,
    country3DB
};

这只是一些示例代码,需要重构才能有用(引入一些循环等)。它应该只向您展示如何在单个应用程序中使用多个数据库的想法。如果您想使用,例如country1数据库在某个地方,您只需做

import { country1DB } from './databases';
country1DB.User.findAll({...});

上面的代码将在先前指定的country1数据库中执行SELECT * FROM users。示例express路由看起来像以下内容:

import * as databases from './databases';
app.get('/:dbIndex/users', (req, res) => {
    databases['country' + req.params.dbIndex + 'DB'].User.find().then(user => {
        res.json(user.toJSON());
    });
});

或更好的是,您可以编写一些middleware功能,这些功能将在每个请求之前运行,并且负责选择适当的数据库进行进一步操作。

最新更新