Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typeorm

nestjs

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!

like image 466
user7646471 Avatar asked Mar 05 '26 01:03

user7646471


1 Answers

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();
  }
}

like image 92
Troy Kessler Avatar answered Mar 07 '26 09:03

Troy Kessler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!