将所有请求路由到特定数据库 express node js

Route all the requests to specific database express node js

我正在开发一个 saas 应用程序(每个客户端都有单独的数据库)后端 uisng 节点 js、express 和 mysql 以及 sequelize orm。 Url 是:http://example.com/customer/api 这里的客户数量可以达到 1000 人 现在我需要获取该客户名称并连接到那里的数据库,然后将所有请求路由到该数据库。 每当有请求时,就必须这样做。 // 首先连接到客户数据库 然后 app.use('/api', 路线) 此处的路线包含应用程序中的所有路线。 如何处理?我需要一种方法在请求到达时连接到该客户数据库,然后在该客户数据库上处理请求。

如何获取对应的数据库? 中间件可以在不同数据库之间路由,例如用户“x”发出请求。中间件为用户 x 搜索对应的数据库,并将该数据库的连接字符串放入 req. 请求的处理程序然后获取 conn 字符串并连接到相应的数据库。然后可以使用 node-cache 缓存连接,然后在客户需要另一个请求时检索连接。

编辑:

一些代码

var express = require('express');
var app = express();
    
var getDb = function (req, res, next) {
  req.body.username //get for example the username
  //search for the corresponding connection string in the database
  //then add it to the request
  req.databaseString = connString //connString --the connection 
  // String you got earlier
  next();
};
    
app.use(getDb);
    
app.get('/makeSomething', function (req, res) {
  //connect to db with req.databaseString
  //do what you wanna do
    
  res.send('done');
});
    
app.listen(3000);

添加到您上面的评论中。 “我的问题是这里的路由是否知道要连接哪个数据库?” 路由在查看 req 并查找连接字符串时知道这一点。通过连接字符串,他们知道要使用哪个数据库。