网络编程 
首页 > 网络编程 > 浏览文章

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

(编辑:jimmy 日期: 2024/5/18 浏览:3 次 )

一般开发过程中不不会根据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"
}

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、使用命令创建一个过滤器

nest g f filters/httpException

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
    "htmlcode">
...
import { HttpExceptionFilter } from './filters/http-exception.filter';

async function bootstrap() {
 ...
 // 全局注册错误的过滤器
 app.useGlobalFilters(new HttpExceptionFilter());
}
bootstrap();

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

{
 "statusCode": 400,
 "error": "Bad Request",
 "data": {
  "message": [
   {
    "age": "必须的整数"
   }
  ]
 },
 "message": '请求失败',
 "code": 1,
 "url": "/api/v1/cat"
}

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

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: '请求成功',
    };
   }),
  );
 }
}

3、全局注册

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

async function bootstrap() {
 ...
 // 全局注册拦截器
 app.useGlobalInterceptors(new TransformInterceptor());
 ...
}
bootstrap();

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": "请求成功"
}

上一篇:JavaScript实现H5接金币功能(实例代码)
下一篇:NestJs使用Mongoose对MongoDB操作的方法
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。
友情链接:杰晶网络 DDR爱好者之家 南强小屋 黑松山资源网 白云城资源网