【问题标题】:How to set .env variables in a module import / configuration如何在模块导入/配置中设置 .env 变量
【发布时间】:2020-01-18 04:40:54
【问题描述】:

我想在我的应用中使用.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 {}

【问题讨论】:

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


    【解决方案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_port)}/${configService.get(db_name)}`,
      }),
      inject: [ConfigService],
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-31
      相关资源
      最近更新 更多