简体   繁体   English

如何基于登录名在Express.js中动态分配数据库路径?

[英]How can I dynamically assign a database path in Express.js based on login?

I have a backend service that I would like to use as a single point of entry for my web application, and dynamically assign a database path based on the user login. 我有一个后端服务,我想将其用作Web应用程序的单个入口点,并根据用户登录动态分配数据库路径。 I realize that this is not a scalable solution. 我意识到这不是可扩展的解决方案。 I intend to use it during a testing period with several clients (accessing the ALPHA database), and also setting up a demo (accessing the SAND database). 我打算在测试期间与多个客户端(访问ALPHA数据库)一起使用它,并设置一个演示(访问SAND数据库)。 I have the following module that I have written as a simple test to see if the login is for the demo user, all other logins will go to the other resource: 我编写了以下模块作为一个简单的测试,以查看该登录名是否针对演示用户,所有其他登录名将转到其他资源:

config.js

var express         = require('express');
var app             = express();

module.exports.dbPath = function  (login){
    console.log('login - ', login);
    if (login === 'demo@mysite.com'){
        return process.env.DB_SAND;
    } else {
        return process.env.DB_ALPHA;
    }
};

My question is, how can I manage each unique login and assign a globally accessible reference for that session to direct each user session consistently to the correct database? 我的问题是,我该如何管理每个唯一的登录并为该会话分配一个全局可访问的引用,以将每个用户会话一致地定向到正确的数据库? Am I overcomplicating this? 我使这个复杂化了吗? If there is a different approach that would be a better practice I would welcome a suggestion in another direction. 如果有其他更好的做法,我欢迎朝另一个方向提出建议。

I would use it as a middleware, and attach it to the req object for each user, something similar this: 我将其用作中间件,并将其附加到每个用户的req对象,类似于以下内容:

module.exports = {
    dbPath: function(req, res, next){
       var login = req.body.login;
       console.log('login - ', login);
       if (login === 'demo@mysite.com'){
          req.dbPath = 'DB_SAND';
       } else {
          req.dbPath = 'DB_ALPHA';
       }
       next();
    }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM