Nestjs加載和讀取配置

在 NestJS 中,我們可以使用 ConfigModule 模塊來加載自定義配置。

首先,我們需要安裝 @nestjs/config 包:

npm install --save @nestjs/config

然后,在你的應(yīng)用程序模塊中使用 ConfigModule

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: '.env', // 可選的,指定環(huán)境變量文件的路徑
      isGlobal: true, // 可選的,表示配置模塊是否應(yīng)該是全局的,默認(rèn)為 true
    }),
  ],
})
export class AppModule {}

ConfigModule.forRoot 中,可以使用一些配置選項(xiàng)來指定加載配置的行為和規(guī)則。常用的選項(xiàng)包括:

  • envFilePath: 指定環(huán)境變量文件(如 .env)的路徑,可以包含多個(gè)不同環(huán)境的配置,如 .env.production、.env.test 等,還可以通過 process.env.NODE_ENV 環(huán)境變量動(dòng)態(tài)加載相應(yīng)的配置。
  • isGlobal: 指定是否將配置模塊設(shè)置為全局的,如果設(shè)置為 true(默認(rèn)值),則可以在任何地方使用配置服務(wù),否則需要在每個(gè)需要使用配置的模塊中引入 ConfigModule。

在配置模塊加載完成后,就可以使用 ConfigService 服務(wù)來讀取配置了,例如:

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class AppService {
  constructor(private configService: ConfigService) {}

  getPort(): number {
    return this.configService.get<number>('APP_PORT') || 3000;
  }

  getDatabaseConfig(): { host: string, port: number, username: string, password: string } {
    return {
      host: this.configService.get<string>('DB_HOST', 'localhost'),
      port: this.configService.get<number>('DB_PORT', 5432),
      username: this.configService.get<string>('DB_USERNAME', 'admin'),
      password: this.configService.get<string>('DB_PASSWORD', 'password'),
    };
  }
}

以上代碼中,我們使用 ConfigService 服務(wù)來讀取了兩個(gè)配置項(xiàng),分別是 APP_PORTDB_* 相關(guān)的配置項(xiàng)。如果獲取不到配置項(xiàng),就會(huì)使用指定的默認(rèn)值。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容