如何在模块导入/配置中设置.env变量

时间:2019-09-17 10:19:40

标签: javascript node.js typescript dependency-injection nestjs

我想在我的应用中使用.env文件。

我为此创建了两个文件(一个模块和一项服务):

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];
    }

}

问题是在我的主模块中,我想连接到mongo,但是我不知道如何在声明以下模块时恢复变量:

  

实际上,这是一个为我提供信息的类

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 个答案:

答案 0 :(得分:1)

看看文档中的async configuration section。使用异步配置,您可以注入依赖项并将其用于配置:

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_name)}/${configService.get(db_name)},
  }),
  inject: [ConfigService],
});