NestJS学习05 - 配置全局返回参数

432 阅读1分钟

全局返回参数

一般项目的返回参数应该包括以下的内容:

{
    data, // 数据
    status: 0, // 接口状态值
    extra: {}, // 拓展信息
    message: 'success', // 异常信息
    success:true // 接口业务返回状态
}

想要输出上述标准的返回参数格式的话:

第一步:

新建 src/common/interceptors/transform.interceptor.ts 文件:

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

interface Response<T> {
  data: T;
}

@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, Response<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<Response<T>> {
    return next.handle().pipe(
      map((data) => ({
        data,
        status: 0,
        extra: {},
        message: 'success',
        success: true,
      })),
    );
  }
}

第二步: 修改 main.ts 文件,添加 useGlobalInterceptors 全局拦截器,处理返回值

app.useGlobalInterceptors(new TransformInterceptor());

然后我们再次访问之前的请求,就能获取到标准格式的接口返回值了