其实这也是一个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 {
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('node_env') // log:mock | staging
总结,我们可以将需要注入的服务provide到模块中,同时我们也要将需要注入的服务、拦截器、守卫等也provide到模块中。这样我们就可以通过注入获取各个服务了。



