拦截器

拦截器具有一系列有用的功能,这些功能受面向切面编程(AOP)技术的启发。它们可以:

  • 在函数执行之前/之后绑定额外的逻辑
  • 转换从函数返回的结果
  • 转换从函数抛出的异常
  • 扩展基本函数行为
  • 根据所选条件完全重写函数 (例如, 缓存目的)

实现返回的格式统一为,

{
  data, //数据
  status:0,
  message:"成功",
  success:true
}

新建 common 文件夹 创建 response.ts

import { Injectable, NestInterceptor, CallHandler, ExecutionContext } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

// 定义标准响应结构
interface ResponseFormat<T> {
  data: T; // 实际数据
  status: number; // 状态码
  success: boolean; // 是否成功
  message: string; // 消息
}

@Injectable()
export class ResponseInterceptor<T = any> implements NestInterceptor<T, ResponseFormat<T>> {
  constructor(private readonly options?: { message?: string; status?: number }) {}
  intercept(context: ExecutionContext, next: CallHandler<T>): Observable<ResponseFormat<T>> {
    return next.handle().pipe(
      map((rawData: T) => ({
        data: rawData, // 使用泛型传递的类型
        status: this.options?.status ?? 200,
        success: true,
        message: this.options?.message || 'Success',
      }))
    );
  }
}

在 main.ts 注册

import { ResponseInterceptor } from './common/response';
app.useGlobalInterceptors(new ResponseInterceptor());
Last Updated:
Contributors: haizhiguang