小编yoh*_*yoh的帖子

NestJS:按请求(子域)进行数据库连接(TypeORM)

我正在尝试通过Nest / TypeORM构建SAAS产品,并且需要按子域配置/更改数据库连接。

customer1.domain.com => connect to customer1 database
customer2.domain.com => connect to customer2 database
x.domain.com => connect to x database
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点 ?使用拦截器或请求上下文(或Zone.js)?

我不知道如何开始。有人已经这样做了吗?


WIP:我目前在做什么:

  1. 将所有连接设置添加到ormconfig文件中
  2. 在所有路由上创建中间件以将子域注入res.locals(实例名称)并创建/警告typeorm连接

    import { Injectable, NestMiddleware, MiddlewareFunction } from '@nestjs/common';
    import { getConnection, createConnection } from "typeorm";
    
    @Injectable()
    export class DatabaseMiddleware implements NestMiddleware {
        resolve(): MiddlewareFunction {
          return async (req, res, next) => {
              const instance = req.headers.host.split('.')[0]
              res.locals.instance = instance
    
              try {
                  getConnection(instance)
              } catch (error) {
                  await createConnection(instance)
              }
    
              next();
          }; …
    Run Code Online (Sandbox Code Playgroud)

typeorm nestjs

7
推荐指数
1
解决办法
2014
查看次数

标签 统计

nestjs ×1

typeorm ×1