拦截器
拦截器具有一系列有用的功能,这些功能受面向切面编程(AOP)技术的启发。它们可以:
- 在函数执行之前/之后绑定额外的逻辑
- 转换从函数返回的结果
- 转换从函数抛出的异常
- 扩展基本函数行为
- 根据所选条件完全重写函数 (例如, 缓存目的)
我们现在没有给我们的Nestjs规范返回给前端的数据格式,现在比较乱
我们想给它返回一个标准的json格式,就要给我们的数据做一个全局form
{
data, //数据
status:0,
message:"成功",
success:true
}
新建common文件夹,创建 response.ts
Nest Js配合Rxjs格式化数据
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from "@nestjs/common";
import { Observable, map } from "rxjs";
@Injectable()
export default class Response<T> implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler<any>): Observable<any> | Promise<Observable<any>> {
return next.handle().pipe(map(data => {
return {
data,
status: 0,
success: true,
message: "成功"
}
}))
}
}
在main.ts注册
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { VersioningType } from '@nestjs/common';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import Response from './common/response'
async function bootstrap() {
const app = await NestFactory.create<NestExpressApplication>(AppModule);
app.enableVersioning({
type: VersioningType.URI
})
app.useGlobalInterceptors(new Response())
await app.listen(3000);
}
bootstrap();
访问地址http://localhost:3000,已经返回成我们需要的数据格式了