Change database connection depending on route in express.js with sequelize

别说谁变了你拦得住时间么 提交于 2019-12-23 15:55:22

问题


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

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

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

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?

*login only occurs once


回答1:


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

Router.js

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.

I hope this helps!




回答2:


I think is better to change collections depending on the route. Have foo_tasks collection and bar_tasks collection in the same database.

Or have the attribute type in the tasks collection that specifies if the task is a "foo task" or a "bar task".



来源:https://stackoverflow.com/questions/30202056/change-database-connection-depending-on-route-in-express-js-with-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!