【问题标题】:NestJS Export. connection, postgres multi tenancyNestJS 导出。连接,postgres 多租户
【发布时间】:2021-07-21 11:29:04
【问题描述】:

我试图使用 postgres 实现多租户架构。它在租户服务上按预期工作。我想将此 CONNECTION 导入到名为 shop 的不同模块中。我该怎么做。您当前看到的是租户模块。

import { TenantService } from './tenant.service';
    import { TenantController } from './tenant.controller';

import { Global, Module, Scope } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Connection, createConnection, getConnectionManager } from 'typeorm';

import * as tenantsOrmconfig from '@config/typeorm/tenant-ormconfig';
import * as ormconfig from '@config/typeorm/ormconfig';
import { ShopModule } from './shop/shop.module';
import { AwsService } from '@config/aws';

const connectionFactory = {
  provide: 'CONNECTION',
  scope: Scope.REQUEST,
  useFactory: async (req) => {
    const teamId = req.headers['x-team-id'];
    console.log('xxxxxxxxxxxxxxxxxxx', teamId);

    if (teamId) {
      const connectionName = `${teamId}`;
      const connectionManager = getConnectionManager();

      if (connectionManager.has(connectionName)) {
        const connection = connectionManager.get(connectionName);
        return Promise.resolve(
          connection.isConnected ? connection : connection.connect(),
        );
      }

      return createConnection({
        ...tenantsOrmconfig,
        entities: [
          ...(tenantsOrmconfig as any).entities,
          ...(ormconfig as any).entities,
        ],
        name: connectionName,
        type: 'postgres',
        schema: connectionName,
      });
    }
  },
  inject: [REQUEST],
};

@Module({
  imports: [ShopModule],
  controllers: [TenantController],
  providers: [connectionFactory, TenantService],
  exports: ['CONNECTION'],
})
export class TenantModule {}

在tenantService中的使用方法如下

export class TenantService {
  gameRepository;
  constructor(@Inject('CONNECTION') connection) {
    this.gameRepository = connection.getRepository(TenantEntity);
   
  }

【问题讨论】:

    标签: node.js typescript express nestjs nestjs-config


    【解决方案1】:

    我通过使用 @Global() 装饰器解决了这个问题。它使租户模块成为全球性的,以便可以在项目的任何地方导入它。 在其他模块上导入它时,我使用了

    imports: [forwardRef(() => TenantModule)],
    

    #tenant 具有多租户连接属性的模块

    @Global()
    @Module({
      imports: [ShopModule],
      controllers: [TenantController],
      providers: [connectionFactory, TenantService],
      exports: ['CONNECTION'],
    })
    export class TenantModule {}
    

    我需要模式选择的#shop 模块

    @Module({
      imports: [forwardRef(() => TenantModule)],
      controllers: [ShopController],
      providers: [ShopService, AwsService],
    })
    export class ShopModule {}
    

    【讨论】:

      猜你喜欢
      • 2021-05-21
      • 1970-01-01
      • 2021-07-11
      • 1970-01-01
      • 2019-09-28
      • 2017-08-01
      • 1970-01-01
      • 2013-05-16
      • 1970-01-01
      相关资源
      最近更新 更多