0

我试图使用 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);
   
  }
4

1 回答 1

0

我通过使用 @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-04-28T12:46:39.893 回答