NestJs - TypeORM 配置可以工作,但不能与 ConfigService 一起使用

Que*_*n3r 4 typeorm nestjs

我想使用 NestJs 和 TypeORM 创建一个 REST API。在我的app.module.ts中,我加载 TypeORM 模块

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'postgres',
      host: 'localhost',
      port: 5432,
      username: 'postgres',
      password: 'postgres',
      database: 'api',
      entities: [`${__dirname}/**/*.entity.{ts,js}`],
      synchronize: true,
    }),
  ],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

目前运行良好。我想从外部 .env 文件加载配置,以便从文档中加载

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

从这里开始

NestJS 将 ConfigService 与 TypeOrmModule 结合使用

我在根项目目录中创建了一个 .env 文件,内容如下

DATABASE_TYPE = postgres
DATABASE_HOST = localhost
DATABASE_PORT = 5432
DATABASE_USERNAME = postgres
DATABASE_PASSWORD = postgres
DATABASE_NAME = api
DATABASE_SYNCHRONIZE = true
Run Code Online (Sandbox Code Playgroud)

接下来我将代码更新为

@Module({
  imports: [
    ConfigModule.forRoot(),
    TypeOrmModule.forRootAsync({
      imports: [ConfigModule],
      useFactory: async (configService: ConfigService) => ({
        type: configService.get<any>('DATABASE_TYPE'),
        host: configService.get<string>('DATABASE_HOST'),
        port: configService.get<number>('DATABASE_PORT'),
        username: configService.get<string>('DATABASE_USERNAME'),
        password: configService.get<string>('DATABASE_PASSWORD'),
        database: configService.get<string>('DATABASE_NAME'),
        entities: [`${__dirname}/**/*.entity.{ts,js}`],
        synchronize: configService.get<boolean>('DATABASE_SYNCHRONIZE'),
      }),
      inject: [ConfigService],
    }),
  ],
})
export class AppModule {}
Run Code Online (Sandbox Code Playgroud)

不幸的是我在启动时收到此错误

[Nest] 28257   - 01/06/2020, 7:19:20 AM   [ExceptionHandler] Nest can't resolve dependencies of the TypeOrmModuleOptions (?). Please make sure that the argument ConfigService at index [0] is available in the TypeOrmCoreModule context.

Potential solutions:
- If ConfigService is a provider, is it part of the current TypeOrmCoreModule?
- If ConfigService is exported from a separate @Module, is that module imported within TypeOrmCoreModule?
  @Module({
    imports: [ /* the Module containing ConfigService */ ]
  })
 +1ms
Run Code Online (Sandbox Code Playgroud)

当我在bootstrap函数中将配置记录到main.ts中时,我从 .env 文件中获得了正确的配置。

我该如何修复该错误?

Jay*_*iel 9

需要发生以下两件事之一:

1)您需要ConfigModule通过将isGlobal: true选项传递给来使您的全局化ConfigModule.forRoot()。如果您这样做,那么您可以删除TypeormModule.forRootAsync()(它是一个全局模块,并且可以在任何地方使用它的提供程序)中的导入

2)制作另一个模块(MyConfigModule或其他东西),importsConfigModule配置exportsCofnigModule. 然后你可以在配置中更改ConfigModule.forRoot()为。MyConfigModuleAppModuleimports: [ConfigModule]imports: [MyConfigModule]TypeormModule.forRootAsync()