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