user7646471
user7646471

Reputation: 372

Nest.js TypeORM How to switch database connection at runtime depending on header

I have two databases and want to use one of them depending on a header I send with http request.

Anyone has an idea how I can switch the TypeORM connection dynamically in Nest? Thx!

Upvotes: 3

Views: 5574

Answers (2)

Shane Richards
Shane Richards

Reputation: 341

Try using middleware to parse the values and request scoped services to chose the correct connection at runtime as described here, How can i setup multitenant in NESTJS.

Upvotes: 0

Troy Kessler
Troy Kessler

Reputation: 387

It is quite easy to use multiple databases with nestjs. The official documentation has a great explanation of setting them up https://docs.nestjs.com/techniques/database#multiple-databases

First you can register your databases in the AppModule

const defaultOptions = {
  type: 'postgres',
  port: 5432,
  username: 'user',
  password: 'password',
  database: 'db',
  synchronize: true,
};

@Module({
  imports: [
    TypeOrmModule.forRoot({
      ...defaultOptions,
      name: 'db_1',
      host: 'host_1',
      entities: [Entity1],
    }),
    TypeOrmModule.forRoot({
      ...defaultOptions,
      name: 'db_2',
      host: 'host_2',
      entities: [Entity2],
    })
  ],
})
export class AppModule {}

With that you can inject your connection and choose between them

@Module({
  imports: [
    TypeOrmModule.forFeature([Entity1], 'db_1'),
    TypeOrmModule.forFeature([Entity2], 'db_2'),
  ],
})
export class AppModule {}
@Injectable()
export class PersonService {
  constructor(
    @InjectRepository('db_1')
    private readonly repo_1: Repository<Entity1>,
    @InjectRepository('db_2')
    private readonly repo_2: Repository<Entity2>,
  ) {}

  public fetchData(db_1: boolean) {
    if (db_1) {
      return this.repo_1.find();
    }
    return this.repo_2.find();
  }
}

Upvotes: 4

Related Questions