Search code examples
javascriptnode.jstypescriptnestjstypeorm

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.


Solution

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