Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use configService in App.Module.ts?

I am building RESTful service with NestJs, I have followed the example to build configurations for different environments. It works well for most code. However I am wondering if I can use it in my 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 { }

As you can see I do want to move the MongoDb Url info outside the code and I am thinking to leverage .env files. But after some attempts, it does not seem to work.

Of course I can use ${process.env.MONGODB_URL || 'localhost'} instead, and set the environment variables. I'm still curious if I can make the configService work.

like image 574
hardywang Avatar asked Feb 05 '19 13:02

hardywang


1 Answers

You have to use a dynamic import (see Async configuration). With it, you can inject dependencies and use them for the initialization:

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],
}),
like image 169
Kim Kern Avatar answered Sep 21 '22 13:09

Kim Kern