nestJS 接口包装

发布于 2024-03-19  164 次阅读


1.创建文件夹 response

2.成功获取数据 包装

(1)创建 successResponse.ts文件 并添加如下代码

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

interface Data<T> {
  data: T;
}

@Injectable()
export class SuccessResponse<T> implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<Data<T>> {
    return next.handle().pipe(
      map((data) => {
        return {
          code: 1,
          data, // data为你操作返回的数据        
          message: '操作成功',
          success: true,
        };
      }),
    );
  }
}

(2)在main.ts中引入如下代码

app.useGlobalInterceptors(new SuccessResponse());

2.失败包装

(1)在response下创建 failResponse.ts文件

import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';
import { Response, Request } from 'express';

@Catch()
// 接口异常拦截器
export class HttpFaild implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const request = ctx.getRequest<Request>();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();
    console.log(status, 'status');

    response.status(status).json({


      msg: exception.message,

      code: 2,
    });
  }
}

(2)在main.ts中引入如下代码

app.useGlobalFilters(new HttpFaild());

(3)使用

throw new HttpException('数据获取出错', HttpStatus.FORBIDDEN);

一个练习时长还差一年半的切图仔,有需求可联系 QQ:963827384
最后更新于 2024-03-19