Nest.js TypeORM如何在运行时根据标头切换数据库连接

时间:2020-01-27 11:41:34

标签: nestjs typeorm

我有两个数据库,并希望根据我随http请求发送的标头使用其中一个数据库。

任何人都知道如何在Nest中动态切换TypeORM连接?谢谢!

2 个答案:

答案 0 :(得分:2)

使用带有Nestjs的多个数据库非常容易。官方文档对设置它们https://docs.nestjs.com/techniques/database#multiple-databases

有很好的解释

首先,您可以在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 {}

这样您就可以注入连接并在它们之间进行选择

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

答案 1 :(得分:0)

请尝试使用中间件来解析值,并请求范围内的服务在运行时选择正确的连接,如How can i setup multitenant in NESTJS所述。