使用node+express+sequelize+(mysql或postgres)构建saas产品

yebdmbv4  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(364)

我们正在计划构建一个基于saas的产品,所以主要经过大量的搜索,我们发现有三种数据库方法来设计saas产品。
每个租户的独立数据库
每个租户的单独架构
所有租户的共享架构和一个数据库(但将使用租户id进行查询)
所以我们计划进入方案2,
所以最初我们使用mysql,但是我们没有发现如何在mysql中获得多个模式,我们使用sequelize作为orm。
在大量的google搜索之后,我们发现许多基于多租户的产品正在使用postgresql作为强大的模式方法,因此我们尝试了以下库:
https://github.com/westmark/sequelize-multi-tenant-enhancer
我们尝试了这个库的基于多模式的方法,但是数据没有按照租户显示,而且我在github中打开了一个问题,
所以,如果你有任何想法,或任何帮助我构建saas产品的帖子,请帮助我
注意:我的堆栈:node+express+angular+mysql或postgres
我的问题是如何在postgres中使用多个模式?

jhdbpxl9

jhdbpxl91#

最后,我决定使用选项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));
};

我正在设置我的postgres连接
为了测试,我创建了一个名为“inventory”的表
在我的应用程序中,一个在线的人来注册,注册的时候我把业务代码存储到我的业务表中(业务表来自单独的数据库,这是一个超级主应用程序数据库),所以我在postgres中查找业务代码和循环并生成动态模式
现在看一下我的api,我正在基于req.user.code(来自登录会话)执行crud,最后根据特定的模式匹配显示数据,
最后,我为每个客户机提供了干净的独立模式
谢谢!

相关问题