Nestjs加载和读取配置

2023-08-24  本文已影响0人  陈晓青_57a8

在 NestJS 中,我们可以使用 ConfigModule 模块来加载自定义配置。

首先,我们需要安装 @nestjs/config 包:

npm install --save @nestjs/config

然后,在你的应用程序模块中使用 ConfigModule

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

@Module({
  imports: [
    ConfigModule.forRoot({
      envFilePath: '.env', // 可选的,指定环境变量文件的路径
      isGlobal: true, // 可选的,表示配置模块是否应该是全局的,默认为 true
    }),
  ],
})
export class AppModule {}

ConfigModule.forRoot 中,可以使用一些配置选项来指定加载配置的行为和规则。常用的选项包括:

在配置模块加载完成后,就可以使用 ConfigService 服务来读取配置了,例如:

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 服务来读取了两个配置项,分别是 APP_PORTDB_* 相关的配置项。如果获取不到配置项,就会使用指定的默认值。

上一篇 下一篇

猜你喜欢

热点阅读