通过env搭配@nestjs/config实现 环境配置。
安装依赖
$ yarn add @nestjs/config
$ yarn add cross-env -D
文件配置
创建环境配置文件
# 环境变量文件夹
/env
# 默认兜底配置
/env/.env
# 开发环境
/env/.env.development
# 本地环境
/env/.env.local
# 生产环境
/env/.env.production
# ts 配置对象
/config
# 默认配置
/config/configuration.ts
config TS
/config/configuration.ts
/**
* 配置类型
*/
const configMdole = {
// 端口
port: parseInt(process.env.PORT) || 8088,
host: process.env.HOST,
// jwt secret
jwtsecret: process.env.JWT_CONSTANTS,
/**
* 项目部署统一前缀
*/
prefix: process.env.PREFIX,
/**
* 对称加密的密钥
*/
signHmac: process.env.SIGN_HMAC,
};
/**
* 默认配置导出
*/
export default () => configMdole;
/**
* 配置类型
*/
export type ConfigurationType = typeof configMdole;
- 修改 /src/app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ConfigModule } from '@nestjs/config';
import configuration from 'config/configuration';
// 环境变量加载
const envFilePath = ['env/.env'];
if (process.env.NODE_ENV) {
envFilePath.unshift(`env/.env.${process.env.NODE_ENV}`);
}
@Module({
imports: [
ConfigModule.forRoot({
load: [configuration],
envFilePath,
}),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
main.ts 使用配置
const configService = app.get(ConfigService);
const value = configService.get('xxxx');
// 获取环境变量
const dbUser = configService.get<string>('DATABASE_USER');
// 获取自定义配置值
const dbHost = configService.get<string>('database.host');
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ConfigService } from '@nestjs/config';
import { Logger } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const configService = app.get(ConfigService);
const PORT = configService.get('PORT');
const HOST = configService.get('HOST');
const PREFIX = `/${configService.get('PREFIX')}`;
const PROJECTNAME = configService.get('PROJECTNAME');
const logger: Logger = new Logger('main.ts');
await app.listen(PORT, HOST, () => {
logger.log(
`[${PROJECTNAME}]已经启动,接口请访问:
http://${HOST}:${PORT}${PREFIX}
http://${HOST}:${PORT}${PREFIX}/graphiql
`,
);
});
}
bootstrap();
services 使用配置
依赖注入
import { HttpService } from '@nestjs/axios';
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectModel } from '@nestjs/sequelize';
import { AppJobModel } from 'src/model/customer/app-job.model';
import { IBaseService } from 'src/utils/base-service';
import { CONST_CONFIG } from 'src/utils/const-config';
@Injectable()
export class AppJobService extends IBaseService<AppJobModel> {
constructor(
@InjectModel(AppJobModel)
private appJobModel: typeof AppJobModel,
private readonly httpService: HttpService,
private configService: ConfigService,
) {
super();
}
/**
* 获取java 任务信息
* @param jobId
*/
async queryJavaJob(jobId: string) {
const url = `${this.configService.get<string>(
CONST_CONFIG.JAVASERVERURL,
)}/app-web/marketing/bee/task?taskCode=${jobId}`;
return this.httpService.axiosRef
.get(url)
.then((res) => res.data)
.catch((error) => {
console.log(error);
throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
});
}
}
网友评论