[Nestjs] 手摸手之简单封装API接口的返回结果

文章介绍了如何在NestJs框架中自定义统一的响应拦截器,用于处理成功、错误和分页响应,提供代码示例展示了如何在控制器中使用这些拦截器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

介绍:在 NestJs 中,你可以自定义一个统一的响应封装来支持成功、错误和分页响应。

代码示例:

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

// 统一成功响应的数据结构
export interface SuccessResponse<T> {
  code: number;
  message: string;
  data: T;
}

// 统一错误响应的数据结构
export interface ErrorResponse {
  code: number;
  message: string;
}

// 统一分页响应的数据结构
export interface PaginatedResponse<T> {
  code: number;
  message: string;
  data: T[];
  total: number;
}

@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, SuccessResponse<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<SuccessResponse<T>> {
    return next.handle().pipe(
      map(data => ({
        code: 0, // 自定义成功响应的状态码
        message: '请求成功', // 自定义成功响应的消息
        data,
      })),
    );
  }
}

@Injectable()
export class ErrorInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      catchError(error => {
        return throwError({
          code: error.status || 500, // 自定义错误响应的状态码,默认为 500
          message: error.message || '服务器错误', // 自定义错误响应的消息,默认为 '服务器错误'
        });
      }),
    );
  }
}

然后,在你的控制器中使用这些拦截器来实现统一的响应封装。代码示例:

import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { TransformInterceptor, ErrorInterceptor, SuccessResponse, ErrorResponse, PaginatedResponse } from './common';

@Controller('users')
@UseInterceptors(TransformInterceptor, ErrorInterceptor)
export class UsersController {
  // 成功响应示例
  @Get(':id')
  getUserById(): SuccessResponse<User> {
    const user: User = {
      id: 1,
      name: 'John Doe',
      email: 'johndoe@example.com',
    };

    return user;
  }

  // 错误响应示例
  @Get(':id')
  getUserById(): ErrorResponse {
    throw new NotFoundException('用户未找到');
  }

  // 分页响应示例
  @Get()
  getAllUsers(): PaginatedResponse<User> {
    const users: User[] = [
      {
        id: 1,
        name: 'John Doe',
        email: 'johndoe@example.com',
      },
      {
        id: 2,
        name: 'Jane Smith',
        email: 'janesmith@example.com',
      },
      // ...
    ];

    return {
      data: users,
      total: users.length,
    };
  }
}

这样,当你调用这些接口时,它们会自动使用定义的拦截器进行统一的响应封装,返回相应的数据结构。你可以自行根据需求修改拦截器中的状态码、消息和数据结构等内容。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值