You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NestJS中如何定义仅显示于Swagger的查询参数且不暴露给控制器

解决方案

有两种常用方法可以实现你的需求:让page、limit、sort仅在Swagger文档中展示,同时控制器接收的参数对象不包含这些字段。

方法一:使用class-transformer的@Exclude装饰器(推荐)

利用class-transformer的@Exclude装饰器排除字段,同时保留@ApiProperty让Swagger正常显示参数。

步骤1:修改QueryOptionDto

给需要隐藏的字段添加@Exclude()装饰器:

import { ApiProperty } from '@nestjs/swagger';
import { TransformArray } from '../decorators';
import { Exclude } from 'class-transformer';

export class QueryOptionDto {
  @ApiProperty({ example: 1 })
  @Exclude()
  page?: number;

  @ApiProperty({ example: 10 })
  @Exclude()
  limit?: number;

  @ApiProperty({ example: ['name:asc'] })
  @TransformArray
  @Exclude()
  sort?: string[];
}

步骤2:配置ValidationPipe

确保NestJS启用参数转换,让@Exclude生效。可以全局配置或在控制器方法单独配置:

全局配置(main.ts)

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true, // 启用自动转换DTO
      transformOptions: {
        excludeExtraneousValues: true, // 排除DTO中标记为@Exclude的字段
      },
    }),
  );
  await app.listen(3000);
}
bootstrap();

控制器方法单独配置

import { Query, UsePipes, ValidationPipe } from '@nestjs/common';

class UserController {
  @Get()
  @UsePipes(new ValidationPipe({ transform: true, transformOptions: { excludeExtraneousValues: true } }))
  get(@Query() query: GetUserDto) {
    // 此时query对象仅包含search字段,page/limit/sort已被排除
  }
}

方法二:拆分Swagger DTO与业务DTO

将用于Swagger文档展示的DTO和实际业务接收的DTO分开,彻底隔离字段。

步骤1:创建Swagger专用的基类

// query-option-swagger.dto.ts
import { ApiProperty } from '@nestjs/swagger';
import { TransformArray } from '../decorators';

export class QueryOptionSwaggerDto {
  @ApiProperty({ example: 1 })
  page?: number;

  @ApiProperty({ example: 10 })
  limit?: number;

  @ApiProperty({ example: ['name:asc'] })
  @TransformArray
  sort?: string[];
}

步骤2:创建业务专用的基类

// query-option.dto.ts
export class QueryOptionDto {}

步骤3:定义业务DTO和Swagger展示DTO

// get-user.dto.ts(业务用)
import { ApiProperty } from '@nestjs/swagger';
import { QueryOptionDto } from './query-option.dto';

export class GetUserDto extends QueryOptionDto {
  @ApiProperty({ example: 'John' })
  search?: string;
}

// get-user-swagger.dto.ts(Swagger展示用)
import { ApiProperty } from '@nestjs/swagger';
import { QueryOptionSwaggerDto } from './query-option-swagger.dto';

export class GetUserSwaggerDto extends QueryOptionSwaggerDto {
  @ApiProperty({ example: 'John' })
  search?: string;
}

步骤4:控制器中指定Swagger DTO

import { Get, Query } from '@nestjs/common';
import { ApiQuery } from '@nestjs/swagger';
import { GetUserDto } from './get-user.dto';
import { GetUserSwaggerDto } from './get-user-swagger.dto';

class UserController {
  @Get()
  @ApiQuery({ type: GetUserSwaggerDto })
  get(@Query() query: GetUserDto) {
    // query对象仅包含search字段
  }
}

内容的提问来源于stack exchange,提问作者vy.pham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 07:28:07