Best practice to use config service in NestJS Module

Update Jan 19

HttpModule.registerAsync() was added in version 5.5.0 with this pull request.

HttpModule.registerAsync({
  imports:[ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    baseURL:  configService.get('API_BASE_URL'),
    timeout: 5000,
    maxRedirects: 5,
  }),
  inject: [ConfigService]
}),

Original Post

This problem was discussed in this issue. For the nestjs modules like the TypeOrmModule or the MongooseModule the following pattern was implemented.

The useFactory method returns the configuration object.

TypeOrmModule.forRootAsync({
  imports:[ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    type: configService.getDatabase()
  }),
  inject: [ConfigService]
}),

Although Kamil wrote

Above convention is now applied in all nest modules and will be
treated as a best practice (+recommendation for 3rd party modules).
More in the docs

it does not seem to be implemented for the HttpModule yet, but maybe you can open an issue about it. There are also some other suggestions in the issue I mentioned above.

Also have a look at the official docs with best practices on how to implement a ConfigService.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)