nestjs返回给前端数据格式的封装

一般开发过程中不不会根据httpcode来判断接口请求成功与失败的,而是会根据请求返回的数据,里面加上code字段

一、返回的数据格式对比
1、直接返回的数据格式

{
    "id": 1,
    "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
    "name": "哈士奇1",
    "age": 12,
    "color": null,
    "createAt": "2019-07-25T09:13:30.000Z",
    "updateAt": "2019-07-25T09:13:30.000Z"
}
1
2
3
4
5
6
7
8
9
2、我们自己包装后的返回数据

{
  code: 0,
  message: "请求成功",
  data: {
    "id": 1,
    "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
    "name": "哈士奇1",
    "age": 12,
    "color": null,
    "createAt": "2019-07-25T09:13:30.000Z",
    "updateAt": "2019-07-25T09:13:30.000Z"
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
二、拦截全部的错误请求,统一返回格式
1、使用命令创建一个过滤器

nest g f filters/httpException
1
2、过滤器的代码

import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const message = exception.message.message;
    Logger.log('错误提示', message);
    const errorResponse = {
      data: {
          error: message,
        }, // 获取全部的错误信息
      message: '请求失败',
      code: 1, // 自定义code
      url: request.originalUrl, // 错误的url地址
    };
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    // 设置返回的状态码、请求头、发送错误信息
    response.status(status);
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
3、在main.ts中全局注册

...
import { HttpExceptionFilter } from './filters/http-exception.filter';

async function bootstrap() {
  ...
  // 全局注册错误的过滤器
  app.useGlobalFilters(new HttpExceptionFilter());
}
bootstrap();
1
2
3
4
5
6
7
8
9
4、测试,返回的错误信息

{
  "statusCode": 400,
  "error": "Bad Request",
  "data": {
    "message": [
      {
        "age": "必须的整数"
      }
    ]
  },
  "message": '请求失败',
  "code": 1,
  "url": "/api/v1/cat"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
三、统一请求成功的返回数据
1、创建一个拦截器src/interceptor/transform.interceptor.ts

2、拦截器的代码

import {
  Injectable,
  NestInterceptor,
  CallHandler,
  ExecutionContext,
} from '@nestjs/common';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
interface Response<T> {
  data: T;
}
@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, Response<T>> {
  intercept(
    context: ExecutionContext,
    next: CallHandler<T>,
  ): Observable<Response<T>> {
    return next.handle().pipe(
      map(data => {
        return {
          data,
          code: 0,
          message: '请求成功',
        };
      }),
    );
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
3、全局注册

...
import { TransformInterceptor } from './interceptor/transform.interceptor';

async function bootstrap() {
  ...
  // 全局注册拦截器
  app.useGlobalInterceptors(new TransformInterceptor());
  ...
}
bootstrap();
1
2
3
4
5
6
7
8
9
10
4、测试返回数据

{
  "data": {
    "id": 1,
    "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
    "name": "哈士奇1",
    "age": 12,
    "color": null,
    "createAt": "2019-07-25T09:13:30.000Z",
    "updateAt": "2019-07-25T09:13:30.000Z"
  },
  "code": 0,
  "message": "请求成功"
}
————————————————
版权声明:本文为CSDN博主「水痕01」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/kuangshp128/article/details/97240664

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值