簡體   English   中英

如何在模塊導入/配置中設置 .env 變量

[英]How to set .env variables in a module import / configuration

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

查看文檔中的 異步配置部分 使用異步配置,您可以注入依賴項並將其用於配置:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM