最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

是否有App.Module.ts使用ConfigService的一种方式?

运维笔记admin11浏览0评论

是否有App.Module.ts使用ConfigService的一种方式?

是否有App.Module.ts使用ConfigService的一种方式?

我建立与NestJs RESTful服务,我也跟着example打造针对不同的环境配置。它适用于大多数代码。但是我想知道如果我可以在我的app.module.ts使用它?

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'mongodb',
      host: `${config.get('mongo_url') || 'localhost'}`,
      port: 27017,
      username: 'a',
      password: 'b',
      database: 'my_db',
      entities: [__dirname + '/MyApp/*.Entity{.ts,.js}'],
      synchronize: true}),
    MyModule,
    ConfigModule,
  ],
  controllers: [],
  providers: [MyService],
})
export class AppModule { }

正如你可以看到我确实想迁移MongoDB的地址信息的代码之外,我想利用.env文件。但一些尝试后,它似乎并没有工作。

当然,我可以改用${process.env.MONGODB_URL || 'localhost'},并设置环境变量。我仍然好奇,如果我可以让configService工作。

回答如下:

你必须使用一个dynamic import(见异步配置)。有了它,你可以注入的依赖关系,并将其用于初始化:

TypeOrmModule.forRootAsync({
  imports: [ConfigModule],
  useFactory: (configService: ConfigService) => ({
    type: 'mongodb',
    host: configService.databaseHost,
    port: configService.databasePort,
    username: configService.databaseUsername,
    password: configService.databasePassword,
    database: configService.databaseName,
    entities: [__dirname + '/**/*.entity{.ts,.js}'],
    synchronize: true,
  }),
  inject: [ConfigService],
}),
发布评论

评论列表(0)

  1. 暂无评论