我想使用 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 {}
目前运行良好。我想从外部 .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
接下来我将代码更新为
@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
当我在 bootstrap 函数中将配置记录到 main.ts 中时,我从 .env 文件中获得了正确的配置。
如何修复该错误?
需要发生以下两件事之一:
1) 您需要通过将
ConfigModule
选项传递给 isGlobal: true
来使您的 ConfigModule.forRoot()
全局化。如果这样做,那么您可以删除 TypeormModule.forRootAsync()
中的导入(它是一个全局模块,可以在任何地方使用它的提供程序)
2)制作另一个模块(
MyConfigModule
或其他),imports
带有其配置的ConfigModule
和exports
CofnigModule
。然后您可以在 ConfigModule.forRoot()
中将 MyConfigModule
更改为 AppModule
,并且可以在 imports: [ConfigModule]
配置中将 imports: [MyConfigModule]
更改为 TypeormModule.forRootAsync()
。
@Jay McDoniel 解释的代码翻译
typeorm.config.ts
import { ConfigModule, ConfigService } from '@nestjs/config';
import { TypeOrmModuleAsyncOptions, TypeOrmModuleOptions } from '@nestjs/typeorm';
import { LoggerOptions } from 'typeorm';
export default class TypeOrmConfig {
static getOrmConfig(configService: ConfigService): TypeOrmModuleOptions {
return {
type: 'postgres',
host: configService.get('DB_HOST') || 'localhost',
port: configService.get('DB_PORT') || 5432,
username: configService.get('DB_USERNAME'),
password: configService.get('DB_PASSWORD'),
database: configService.get('DB_NAME'),
entities: [__dirname + '/../**/*.entity{.ts,.js}'],
synchronize:configService.get<boolean>('TYPEORM_SYNCHRONIZE') || false,
logging: configService.get<LoggerOptions>('TYPEORM_LOGGING') || false
};
}
}
export const typeOrmConfigAsync: TypeOrmModuleAsyncOptions = {
imports: [ConfigModule],
useFactory: async (configService: ConfigService): Promise<TypeOrmModuleOptions> => TypeOrmConfig.getOrmConfig(configService),
inject: [ConfigService]
};
app.module.ts
import { LoginModule } from './login/login.module';
import * as redisStore from 'cache-manager-redis-store';
import { ServiceModule } from './service/service.module';
import { UserModule } from './user/user.module';
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { RedisCacheModule } from './redis-cache/redis-cache.module';
import { typeOrmConfigAsync } from './config/typeorm.config';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRootAsync(typeOrmConfigAsync),
UserModule,
ServiceModule,
LoginModule,
RedisCacheModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
如果您使用 Nestjs-query 进行 graphql,这就是这个 library
检查库版本,我用的是5.0.0-alpha-1,就出现了这个问题。快速的解决方案就是恢复到3.0.0版本,这个问题就解决了。