Nestjs加载和读取配置

在 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 中,可以使用一些配置选项来指定加载配置的行为和规则。常用的选项包括:

  • envFilePath: 指定环境变量文件(如 .env)的路径,可以包含多个不同环境的配置,如 .env.production.env.test 等,还可以通过 process.env.NODE_ENV 环境变量动态加载相应的配置。
  • isGlobal: 指定是否将配置模块设置为全局的,如果设置为 true(默认值),则可以在任何地方使用配置服务,否则需要在每个需要使用配置的模块中引入 ConfigModule

在配置模块加载完成后,就可以使用 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_* 相关的配置项。如果获取不到配置项,就会使用指定的默认值。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容