Nest 官方推荐配置模块路线:
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
}),
],
})
export class AppModule {}然后注入 ConfigService:
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');
}
}类比:
ConfigModule
= 机场运行参数中心
= 跑道编号、数据库地址、JWT 密钥、第三方服务地址不要这样写:
const JWT_SECRET = 'abc123';
const DB_URL = 'postgres://localhost:5432/test';因为一旦上线:
- 本地环境
- 测试环境
- 预发环境
- 生产环境
参数全都不同。
配置写死,就像把机场国际航班、货运航班、测试跑道全部写在一张纸上贴死不变。