【问题标题】:How to dynamically connect mysql database according to each client?如何根据每个客户端动态连接mysql数据库?
【发布时间】:2018-11-09 01:59:44
【问题描述】:

我在这里使用 MEAN 堆栈构建 SaaS 产品 M = mysql

我正在使用 sequelize 作为 mysql 的 ORM,我的连接:

const sequelize = new Sequelize('smallscale_superapp', 'root', 'root1', {
  host: '127.0.0.1',
  port: 3306,
  dialect: 'mysql',
  logging: false,
});

例如,我有一个管理员超级应用程序,因此我创建了一项业务,例如业务代码称为 “001abcd”,这个业务代码存储在我的主管理数据库中,然后我告诉我的所有客户转到一个名为“example.com”的特定网址。

因此,如果他们输入 url,主页将看起来像 slack.com,有一个输入框,在硬编码后的值称为 example.com

所以现在我的客户在输入框中输入了我创建的业务代码并存储在我的主数据库中。

将业务代码放入输入框中后,将打开一个名为“001abcd.example.com”的新子域(我正在检查业务代码是否在我的主数据库中匹配,如果匹配我正在创建动态子域)

如果一切顺利,在创建子域客户端页面后将显示为登录屏幕,他们需要在其中注册,并且注册详细信息需要动态地存在 db

注意:我在创建业务时在我的主数据库表中获取客户端数据库、用户名、主机、密码。

如何使用 sequelize mysql 做到这一点?

如何让sequelize connection根据客户端登录动态连接?

正如我之前所说,我的数据库中有客户端 dbname..etc,我正在尝试创建这样的连接:

exports.dynamicDatabase = (req, res) => {
  const { code } = req.params;
  Business.find({
    where: { code },
    raw: true,
  })
    .then((data) => {
      const sequelizeClient = new Sequelize(data.dbname, data.dbusername, data.dbpassword, {
        host: data.dbhost,
        port: 3306,
        dialect: 'mysql',
        logging: false,
      });
    })
    .catch((err) => { res.status(400).send(err.message); });
};

现在在我的这个函数之外,我正在尝试同步表,如下所示:

sequelizeClient.authenticate().then((err) => {
  if (err) {
    console.log('There is connection in ERROR.');
  } else {
    console.log('Dynamic MYSQL Connection has been established successfully');
  }
});
sequelizeClient.sync().then(() => {
  console.log('Dynamic Missing Table Created');
}, (err) => {
  console.log('An error occurred while creating the table:', err.message);
});

变量sequelizeClient在函数内部,无法访问?全球。

所以我在全局范围内创建变量,但是有一个问题

我在函数中有 sequelizeClient 变量,这将在 url 中输入我的域后执行,

但是 sequelizeClient.sync() 不在函数内部,所以当我启动 node server.js 时它会抛出错误:

sequelizeClient.authenticate().then((err) => {
[0]                 ^
[0]
[0] TypeError: Cannot read property 'authenticate' of undefined

【问题讨论】:

  • 不是在程序开始时调用const sequelize = new Sequelize(stuff);,而是等待stuff,然后调用它?我不明白/不明白你的问题是什么,tbh。
  • 我看不懂,有什么基本的例子吗?
  • @ChrisG 每个客户端都有多个子域,我想连接多个数据库。
  • 登录后,调用new Sequelize(...)创建第二个连接。我仍然不明白你在哪里被困住了。
  • 所以我想从 req.user.session 获取 dbname、host 内容?我说的对吗?

标签: javascript mysql node.js sequelize.js saas


【解决方案1】:

最后我尝试了这个并让它工作,但我不知道这是不是好方法,所以告诉我这是否是好方法?

我正在通过用户请求参数获取准确的数据:

let sequelizeClient;
let Login;
exports.getDomain = (req, res) => {
  const { code } = req.params;
  Business.find({
    raw: true,
    where: { code },
  }).then((data) => {
    if (data === null) {
      res.status(400).send(data);
    } else {
      sequelizeClient = new Sequelize(data.dbname, data.dbusername, data.dbpassword, {
        host: data.dbhost,
        port: 3306,
        dialect: 'mysql',
        logging: false,
      });

      // end user connections
      sequelizeClient.authenticate().then((err) => {
        if (err) {
          console.log('There is connection in ERROR.');
        } else {
          console.log(`${data.code} MYSQL Connection has been established successfully`);
        }
      });

      sequelizeClient.sync().then(() => {
        console.log(`${data.code} Missing Table Created`);
      }, (err) => {
        console.log('An error occurred while creating the table:', err.message);
      });

      // mysql tables;
      Login = sequelizeClient.define('login', {
        username: Sequelize.STRING,
        firstName: Sequelize.STRING,
        lastName: Sequelize.STRING,
      });
    }
  });
};

我将表模式变量声明为全局变量,并在我的代码中使用:

// api
exports.signUp = (req, res) => {
  const user = {
    username: req.body.username,
    firstName: req.body.firstName,
    lastName: req.body.lastName,

  };
  Login.create(user)
    .then(data => res.status(200).send(data))
    .catch(Sequelize.ValidationError, err => res.status(422).send(err.errors[0].message))
    .catch(err => res.status(400).send(err.message));
};

【讨论】:

    【解决方案2】:

    是的,经过大量搜索,我发现构建 SaaS 产品有三种数据库方法,

    1. 为每个租户单独的数据库
    2. 为所有租户提供单独的架构(表)和通用的一个数据库
    3. 所有租户共享表和一个数据库

    最后我决定使用选项 2,我改用 Postgresql 而不是 mysql,因为 Postgresql 有基于模式的方法!

    现在是我的最终代码:

    const postgresDB = new Sequelize('postgres://localhost:5432/test_enduser');
    
    postgresDB.authenticate().then((err) => {
      if (err) {
        console.log('There is connection in ERROR.');
      } else {
        console.log('Postgres Connection has been established successfully');
      }
    });
    
    postgresDB.define('inventory', {
      name: Sequelize.STRING,
    });
    
    const createSchema = () => {
      Business.findAll({
        raw: true,
      }).then((data) => {
        data.forEach((client) => {
          postgresDB.createSchema(client.code).then(() => {
            Object.keys(postgresDB.models).forEach((currentItem) => {
              postgresDB.models[currentItem].schema(client.code).sync();
            });
            // new schema is created
            console.log('Postgres schema created');
          }).catch((err) => {
            console.log(err.message);
          });
        });
      });
    };
    createSchema();
    
    
    // apis
    exports.getAllBusiness = (req, res) => {
      postgresDB.models.inventory.schema(req.user.code).findAll()
        .then((results) => {
          res.send(results);
        });
    };
    
    exports.postBusiness = (req, res) => {
      const user = {
        name: req.body.name,
      };
      postgresDB.models.inventory.schema(req.user.code).create(user)
        .then(data => res.status(200).send(data))
        .catch(Sequelize.ValidationError, err => res.status(422).send(err.errors[0].message))
        .catch(err => res.status(400).send(err.message));
    };
    
    1. 我正在设置我的 postgres 连接
    2. 为了测试,我正在创建一个名为“inventory”的表
    3. 在我的应用程序中,出现了一个在线用户并且他注册了,而注册时我将业务代码存储到我的 Business 表中(来自单独数据库的业务表,这是一个超级主应用程序DB),所以我正在寻找业务代码并在 postgres 中循环并制作动态模式

    4. 现在看看我的 api,我正在根据 req.user.code(来自登录会话)进行 CRUD,我终于根据特定模式匹配显示数据,

    所以最后我为每个客户提供了干净的独立架构?

    谢谢!

    【讨论】:

    • 看起来不错的方法,但我很惊讶看到这种方法有超过 1000 个客户。您将为所有 1000 个客户端创建超过 1000 个模式。不会造成性能问题吗?
    猜你喜欢
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 2022-01-17
    • 2020-12-19
    • 2020-03-22
    • 2021-12-27
    • 2013-01-25
    相关资源
    最近更新 更多