2

I am trying to set TypeOrm configuration object using env variables in NestJS. The configuration object should read 'DB_NAME' env variable(set to db.sqlite) set in a .development.env file. The env variable is provided via configService.get('DB_NAME) api of @nestjs/config library. My code in app.module.ts files is as follows:

   import { ConfigModule, ConfigService } from '@nestjs/config';
    import { TypeOrmModule } from '@nestjs/typeorm';


    @Module({
      imports: [ConfigModule.forRoot({
        isGlobal: true,
        envFilePath: `.${process.env.NODE_ENV}.env`
      }), TypeOrmModule.forRootAsync({
        imports: [ConfigModule],
        inject: [ConfigService],
        useFactory: async (config: ConfigService) => {
console.log(config.get('DB_NAME'))  //for testing purpose only; returns undefined 
          return {
            type: 'sqlite',
            database: config.get('DB_NAME'),
            entities: [User, Report],
            synchronize: true
          }
        }
      }), UsersModule, ReportsModule],
      controllers: [AppController],
      providers: [AppService, {
        provide: APP_PIPE,
        useValue: new ValidationPipe({ whitelist: true })
      }],
    })

since config.get('DB_NAME') is undefined, database connection fails and in the console following error is thrown:

DriverOptionNotSetError: Driver option (database) is not set. Please set it to perform connection to the database.

Also receiving undefined while trying to read COOKIE_SESSION env variable inside appModule class using same this.configService.get('COOKIE_SESSION'). The configService in injected using a constructor inside appModule.

Aadil
  • 146
  • 6

2 Answers2

1

try to change your .env file to

.env.development

And rewrite code as

envFilePath: `.env.${process.env.NODE_ENV}`
-1

try adding ConfigService in providers

providers: [AppService, {
  provide: APP_PIPE,
  useValue: new ValidationPipe({ whitelist: true })
}, ConfigService]
fpetrakov
  • 367
  • 1
  • 5
  • 14