我想使用 NestJs 和 TypeORM 创建一个 REST API。在我的应用程序模块.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 {}
目前运行良好。我想从外部 .env 文件加载配置,以便从文档中加载
https://docs.nestjs.com/techniques/database#async-configuration https://docs.nestjs.com/techniques/database#async-configuration
从这里开始
NestJS 将 ConfigService 与 TypeOrmModule 结合使用 https://stackoverflow.com/questions/52570212/nestjs-using-configservice-with-typeormmodule
我在根项目目录中创建了一个 .env 文件,内容如下
DATABASE_TYPE = postgres
DATABASE_HOST = localhost
DATABASE_PORT = 5432
DATABASE_USERNAME = postgres
DATABASE_PASSWORD = postgres
DATABASE_NAME = api
DATABASE_SYNCHRONIZE = true
接下来我将代码更新为
@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 {}
不幸的是我在启动时收到此错误
[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
当我将配置记录在我的main.ts内引导程序函数我从 .env 文件中获得了正确的配置。
我该如何修复该错误?