【问题标题】:Multiple databases from an asynchronous config service?来自异步配置服务的多个数据库?
【发布时间】:2019-07-06 01:19:47
【问题描述】:

NestJS 文档描述了如何定义多个数据库:

https://docs.nestjs.com/techniques/database#multiple-databases

以及使用数据库配置服务进行异步配置:

https://docs.nestjs.com/techniques/database#async-configuration

是否可以通过异步配置服务定义多个数据库?

在实验中,我尝试从我的服务中返回一组选项:

class TypeOrmConfigService implements TypeOrmOptionsFactory {
  createTypeOrmOptions() {
    return [
      { ... },
      { ... }
    ];
  }
}

但这种方法没有运气。

【问题讨论】:

    标签: nestjs


    【解决方案1】:

    看起来对于您想要的每个连接,您都需要创建一个单独的配置实例。我可能建议的是某种工厂,它接受一个名称,也许是数据库连接的配置键,然后使用工厂中的那些来帮助返回预期值。所以文档有一个类似的工厂

    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        type: 'mysql',
        host: configService.getString('HOST'),
        port: configService.getString('PORT'),
        username: configService.getString('USERNAME'),
        password: configService.getString('PASSWORD'),
        database: configService.getString('DATABASE'),
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        synchronize: true,
      }),
      inject: [ConfigService],
    });
    

    你可以创建一个类似的工厂

    const typeOrmFactory = (
      configName: string,
      entities: string[],
      databaseName?: string
    ) => (configService: ConfigService): TypeOrmModuleOptions => ({
      type: 'postgres', // whatever you use
      url: configService.get(configName), // dynamically change which connection you're working with based on the factory input
      name: databaseName || 'default',
      synchronize: true,
      entities // path to the entity/entities you are working with
    });
    

    现在在您的app.module 中,您可以像这样使用工厂

    @Module({
      imports: [
        TypeOrmModule.forRootAsync({
          imports: [ConfigModule],
          useFactory: typeOrmFactory('DATABASE_URL', ['some/path.ts']),
          inject: [ConfigService]
        }),
        TypeOrmModule.forRootAsync({
          imports: [ConfigModule],
          useFactory: typeOrmFactory('DATABASE_URL_2', ['some/other/path.ts'], 'secondaryDatabase'),
          inject: [ConfigServce]
        ],
    })
    export class AppModule {}
    

    确保你告诉 Typescript 你正在返回类型 TypeOrmModuleOptions 否则它会告诉你函数不兼容。如果您愿意,您还可以将大部分配置保存在配置服务和环境变量中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-01
      • 2013-04-20
      • 2018-07-19
      • 2014-04-04
      • 1970-01-01
      相关资源
      最近更新 更多