全书目录

第七篇:NestJS 完全指南 —— 国际机场总调度宇宙

第十五章:配置管理 —— 机场运行参数不能写死在墙上

1 分钟 121 字 第 195 / 962 个阅读单元

Nest 官方推荐配置模块路线:

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

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
  ],
})
export class AppModule {}

然后注入 ConfigService

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

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

  getApiBaseUrl() {
    return this.configService.get<string>('API_BASE_URL');
  }
}

类比:

text
ConfigModule
= 机场运行参数中心
= 跑道编号、数据库地址、JWT 密钥、第三方服务地址

不要这样写:

ts
const JWT_SECRET = 'abc123';
const DB_URL = 'postgres://localhost:5432/test';

因为一旦上线:

  • 本地环境
  • 测试环境
  • 预发环境
  • 生产环境

参数全都不同。

配置写死,就像把机场国际航班、货运航班、测试跑道全部写在一张纸上贴死不变。