看起来对于您想要的每个连接,您都需要创建一个单独的配置实例。我可能建议的是某种工厂,它接受一个名称,也许是数据库连接的配置键,然后使用工厂中的那些来帮助返回预期值。所以文档有一个类似的工厂
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 否则它会告诉你函数不兼容。如果您愿意,您还可以将大部分配置保存在配置服务和环境变量中。