当前位置:网站首页>NestJS环境变量配置,解决如何在拦截器(interceptor)注入服务(service)的问题
NestJS环境变量配置,解决如何在拦截器(interceptor)注入服务(service)的问题
2022-06-27 03:07:00 【acgCode】
其实这也是一个NestJS环境变量配置的过程记录。
在开发过程中我产生了这样一个需求,我需要通过不同的脚本命令启动不同的环境。mock环境中,我要为前端提供虚拟数据;staging环境中,我要作为BFF为前端提供后台传输过来的数据。
在返回数据之前,我需要对数据进行统一格式化。于是我制作了一个拦截器RespTransformInterceptor。
import {
CallHandler,
ExecutionContext,
NestInterceptor,
} from '@nestjs/common';
import {
Observable } from 'rxjs';
import {
map } from 'rxjs/operators';
@Injectable()
export class RespTransformInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map((data) => {
return {
code: 0,
result: data,
};
}),
);
}
}
现在我要对拦截器中的数据进行处理,确保无论哪个环境下,我返回的数据结构都是统一的。那我就要先区分当前的运行环境。
// configuration.ts
// 所有以':mock'结尾的package.json命令,环境为mock;其他为staging
export type ENV_TYPE = 'mock' | 'staging';
export default () => {
const commandSlices = process.env.npm_lifecycle_event.split(':');
const envType = commandSlices[commandSlices.length - 1] as ENV_TYPE;
return {
node_env: envType === 'mock' ? 'mock' : 'staging',
};
};
然后,我们将它导入AppModule中。
// app.module.ts
import {
Module } from '@nestjs/common';
import {
AppController } from './app.controller';
import {
AppService } from './app.service';
import {
LayoutModule } from './common/layout/layout.module';
import {
ConfigModule, ConfigService } from '@nestjs/config';
import {
APP_INTERCEPTOR } from '@nestjs/core';
import {
RespTransformInterceptor } from './common/interceptor/resp-transform.interceptor';
import configuration from './config/configuration';
@Module({
imports: [
LayoutModule,
ConfigModule.forRoot({
load: [configuration], // 配置文件
isGlobal: true, // 提供到全局
}),
],
controllers: [AppController],
providers: [
AppService,
{
provide: APP_INTERCEPTOR,
useClass: RespTransformInterceptor,
},
// 另一种提供到全局的方法
// ConfigService
],
})
export class AppModule {
}
最后,我们需要在拦截器注入服务:
// resp-transform.interceptor.ts
constructor(private readonly configService: ConfigService) {
}
我们可以通过服务的get API获取当前环境。
// resp-transform.interceptor.ts
this.configService.get<string>('node_env') // log:mock | staging
总结,我们可以将需要注入的服务provide到模块中,同时我们也要将需要注入的服务、拦截器、守卫等也provide到模块中。这样我们就可以通过注入获取各个服务了。
边栏推荐
- Web development framework - Express (installation and use, static hosting, routing processing, use of Middleware)
- SAI钢笔工具如何使用,入门篇
- resnet152 辣椒病虫害图像识别1.0
- Svg drag dress Kitty Cat
- 人间清醒:底层逻辑和顶层认知
- Summer planning for the long river
- Servlet and JSP final review examination site sorting 42 questions and 42 answers
- Installing the Damon database using the command line
- ConstraintLayout(约束布局)开发指南
- How to solve the problem of low applet utilization
猜你喜欢

学习太极创客 — MQTT(八)ESP8266订阅MQTT主题

PAT甲级 1026 Table Tennis

【数组】剑指 Offer II 012. 左右两边子数组的和相等 | 剑指 Offer II 013. 二维子矩阵的和

Learning Tai Chi Maker - mqtt Chapter 2 (II) esp8266 QoS application

Pat grade a 1021 deep root

Dameng database installation

three. JS domino JS special effect

Flink learning 5: how it works

Calculation of average wind direction and speed (unit vector method)

How does the brain do arithmetic? Both addition and subtraction methods have special neurons, and the symbol text can activate the same group of cell sub journals
随机推荐
PAT甲级 1026 Table Tennis
bluecms代码审计入门
ESP8266
Easy to use plug-ins in idea
How to solve the problem of low applet utilization
Flink学习3:数据处理模式(流批处理)
2022 Chinese pastry (Advanced) recurrent training question bank and online simulation test
1、项目准备与新建
Questions and answers of chlor alkali electrolysis process in 2022
TopoLVM: 基于LVM的Kubernetes本地持久化方案,容量感知,动态创建PV,轻松使用本地磁盘
【一起上水硕系列】Day 6
Microsoft365开发人员申请
Learn Tai Chi Maker - mqtt (VIII) esp8266 subscribe to mqtt topic
学习太极创客 — MQTT 第二章(二)ESP8266 QoS 应用
TP5 spreadsheet excel table export
TechSmith Camtasia latest 2022 detailed function explanation Download
Uni app's uparse rich text parsing perfectly parses rich text!
Qingscan use
Super detailed, 20000 word detailed explanation, thoroughly understand es!
平均风向风速计算(单位矢量法)