NestJS Export. connection, postgres multi tenancy

217 Views Asked by At

I was trying to implement multi tenancy architecture using postgres. It is working as expected on tenant service. I want import this CONNECTION to a different module called shops.How can I do that. What you are currently seeing is tenant module.

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 {}

how it is used in tenantService is given below

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

There are 1 best solutions below

0
On BEST ANSWER

I solved it by using @Global() decorator. It made the tenant module global so that it can be imported anywhere across the project. While importing it on other module ,I used

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

#tenant module which has multi tenancy connection attributes

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

#shop module where I need schema selection

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