5

I want to use a .env file in my app.

I created two file for that (one module and one service) :

config.module.ts

import {Module} from '@nestjs/common';
import {ConfigService} from './config.service';

@Module({
    providers: [{
        provide: ConfigService,
        useValue: new ConfigService(`${process.env.NODE_ENV || 'development'}.env`),
    }],
    exports: [ConfigService],
})

export class ConfigModule {}

config.service.ts

import * as dotenv from 'dotenv';
import * as fs from 'fs';

export class ConfigService {
    private readonly envConfig: {[key: string]: string};

    constructor(filePath: string) {
        // stock the file
        this.envConfig = dotenv.parse(fs.readFileSync(filePath));
    }

    // get specific key in .env file
    get(key: string): string {
        return this.envConfig[key];
    }

}

The problem is that in my main module I want to connect to mongo but I do not know how I can recover my variables as the module is declared in:

Actually it's a class that gives me the infos

root.module.ts

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { EnvService } from './env';
import { HelloModule } from './module/hello.module';
import { ContentModule } from './module/content.module';
import { CategoriesModule } from './module/categories.module';
import { AuthorModule } from './module/author.module';

const env = new EnvService().getEnv();

@Module({
    imports: [
        // connect to the mongodb database
        MongooseModule.forRoot(`mongodb://${env.db_user}:${env.db_pass}@${env.db_uri}:${env.db_name}/${env.db_name}`, env.db_option),
        // ping module
        HelloModule,
        // data module
        ContentModule,
        CategoriesModule,
        AuthorModule,
    ],
})

export class RootModule {}

1 Answer 1

16

Have a look at the async configuration section in the docs. With an async configuration, you can inject a dependency and use it for the configuration:

MongooseModule.forRootAsync({
  imports: [ConfigModule],
  useFactory: async (configService: ConfigService) => ({
    uri: `mongodb://${configService.get(db_user)}:${configService.get(db_pass)}@${configService.get(db_uri)}:${configService.get(db_port)}/${configService.get(db_name)}`,
  }),
  inject: [ConfigService],
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.