App.Module.ts で configService を使用する方法はありますか? 質問する

App.Module.ts で configService を使用する方法はありますか? 質問する

私はNestJsでRESTfulサービスを構築しており、さまざまな環境用の構成を構築します。ほとんどのコードでうまく機能します。ただし、自分の で使用できるかどうか疑問に思っています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 Url 情報をコードの外部に移動したいので、.envファイルを活用しようと考えています。しかし、何度か試してみましたが、うまくいかないようです。

もちろん、${process.env.MONGODB_URL || 'localhost'}代わりに を使用し、環境変数を設定することもできます。それでも、動作させることができるかどうかは興味がありますconfigService

ベストアンサー1

使用する必要があります動的インポート(見る非同期構成)。これを使用すると、依存関係を注入して初期化に使用することができます。

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],
}),

おすすめ記事