使用 sequelize 根据 express.js 中的路由更改数据库连接

2022-01-19 00:00:00 node.js express javascript sequelize.js

sequelize中是否可以根据路由改变数据库连接?

Is it possible to change the database connection in sequelize depending on the route?

例如,用户可以访问网站中的 2 个不同的安装:- example.com/foo- example.com/bar

For example, Users have access to 2 different installations in a website: - example.com/foo - example.com/bar

登录后,用户会被重定向到 example.com/foo要获取 foo 站点的所有任务,他们需要访问 example.com/foo/tasks

Upon login users are redirected to example.com/foo To get all their tasks for the foo site, they need to visit example.com/foo/tasks

bar 站点使用单独的数据库,因此如果他们想获得 bar 的所有任务,他们必须访问 example.com/bar/任务

The bar site uses a separate database and thus if they want to get all their tasks for bar they have to go to example.com/bar/tasks

每个安装都有自己的数据库,并且所有数据库都具有相同的架构.

Every installation has its own database, and all databases have the same schema.

是否可以根据访问的路由更改数据库连接?

Is it possible to change the database connection depending on which route is visited?

*只登录一次

推荐答案

这是可能的.有很多方法可以做到这一点.以下是我可能会采用的方法.

This is possible. There are a number of ways to do this. Here's how I might approach it.

var router = express.Router()
// This assumes the database is always the 2nd param, 
// otherwise you have to enumerate
router.use('/:database/*', function(req, res, next){
  req.db = req.params.database;
  next();
} 

Connection.js

var fooDB = new Sequelize('postgres://user:pass@example.com:5432/foo');
var barDB = new Sequelize('postgres://user:pass@example.com:5432/bar');
module.exports = {
  foo: fooDB,
  bar: barDB,
}

Tasks.js

 var connection = require('connection);
 function getTasks(req, params){
   var database = connection[req.db]; 
   //database now contains the db you wish to access based on the route.
 }

也就是说,当您想在两者之间复制架构时,您将不得不面对一些有趣的问题,但这可能是另一个问题的最佳选择.

That said, there are some interesting problems you'll have to face when you want to duplicate the schema across both, but that's probably best for another question.

我希望这会有所帮助!

相关文章