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

 7437

这篇文章主要介绍了nestjs返回给前端数据格式封装实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

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

一、返回的数据格式对比

1、直接返回的数据格式

  1. {
  2.     "id": 1,
  3.     "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
  4.     "name": "哈士奇1",
  5.     "age": 12,
  6.     "color": null,
  7.     "createAt": "2019-07-25T09:13:30.000Z",
  8.     "updateAt": "2019-07-25T09:13:30.000Z"
  9. }

2、我们自己包装后的返回数据

  1. {
  2.     code: 0,
  3.     message: "请求成功",
  4.     data: {
  5.         "id": 1,
  6.         "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
  7.         "name": "哈士奇1",
  8.         "age": 12,
  9.         "color": null,
  10.         "createAt": "2019-07-25T09:13:30.000Z",
  11.         "updateAt": "2019-07-25T09:13:30.000Z"
  12.     }
  13. }

二、拦截全部的错误请求,统一返回格式

1、使用命令创建一个过滤器

  1. nest g f filters/httpException

2、过滤器的代码

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

3、在main.ts中全局注册

.

  1. ..
  2. import { HttpExceptionFilter } from './filters/http-exception.filter';
  3.  
  4. async function bootstrap() {
  5.     ...
  6.     // 全局注册错误的过滤器
  7.     app.useGlobalFilters(new HttpExceptionFilter());
  8. }
  9. bootstrap();

4、测试,返回的错误信息

  1. {
  2.     "statusCode": 400,
  3.     "error": "Bad Request",
  4.     "data": {
  5.         "message": [
  6.             {
  7.                 "age": "必须的整数"
  8.             }
  9.         ]
  10.     },
  11.     "message": '请求失败',
  12.     "code": 1,
  13.     "url": "/api/v1/cat"
  14. }

三、统一请求成功的返回数据

1、创建一个拦截器src/interceptor/transform.interceptor.ts

2、拦截器的代码

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

3、全局注册

  1. ...
  2. import { TransformInterceptor } from './interceptor/transform.interceptor';
  3.  
  4. async function bootstrap() {
  5.     ...
  6.     // 全局注册拦截器
  7.     app.useGlobalInterceptors(new TransformInterceptor());
  8.     ...
  9. }
  10. bootstrap();

4、测试返回数据

  1. {
  2.     "data": {
  3.         "id": 1,
  4.         "uuid": "cbbe7abc-b95e-48a0-8d24-b1ac93c45328",
  5.         "name": "哈士奇1",
  6.         "age": 12,
  7.         "color": null,
  8.         "createAt": "2019-07-25T09:13:30.000Z",
  9.         "updateAt": "2019-07-25T09:13:30.000Z"
  10.     },
  11.     "code": 0,
  12.     "message": "请求成功"
  13. }


本文网址:https://www.zztuku.com/index.php/detail-8676.html
站长图库 - nestjs返回给前端数据格式的封装实现
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐