如何在 swagger nestjs 中手动添加摘要和正文

Posted

技术标签:

【中文标题】如何在 swagger nestjs 中手动添加摘要和正文【英文标题】:How to add summary and body manually in swagger nestjs 【发布时间】:2020-05-23 14:58:45 【问题描述】:

我正在尝试在我的 swagger 文档路线中添加摘要,但我无法找到合适的装饰器来定义摘要。

有些路线我没有指定任何 DTO。因此,我想手动为该端点添加请求正文。

user.controller.ts

@Controller('users')
@ApiTags('User')
@ApiBearerAuth()
export class UsersController 

  constructor(private readonly service: UsersService) 

  @Get()
  async findAll() 
    const data = await this.service.findAll();

    return 
      statusCode: 200,
      message: 'Users retrieved successfully',
      data,
    ;
  

auth.controller.ts

  @UseGuards(AuthGuard('local'))
  @Post('login')
  @ApiParam(
    name: 'email',
    type: 'string'
  )
  @ApiParam(
    name: 'password',
    type: 'string'
  )

  async login(@Request() req) 
    return this.authService.login(req.user);
  

【问题讨论】:

【参考方案1】:

对于端点摘要,您可以使用@ApiOperation()。对于架构,您可以使用@ApiResponse()

@Get()
@ApiOperation( summary: 'summary goes here' )
@ApiResponse( status: 200, description: 'description goes here', schema:  ...define schema here...  )
async findAll() 

从此处的文档中了解有关 原始定义 的更多信息:https://docs.nestjs.com/recipes/swagger#raw-definitions

【讨论】:

【参考方案2】:

我建议为所有端点(resp 和 req)创建一个 DTO。

以下是使用 DTO + @ApiProperty 装饰器向架构添加摘要的方法(在您的屏幕截图中,单击红色圈出的区域中的“架构”)

    import  ApiProperty  from '@nestjs/swagger';

    export class ExampleRedditDTO 
        @ApiProperty(
            type: String,
            description: "The target subreddit"
        )
        targetSub!: string;

        @ApiProperty(
            type: Number,
            description: "The number of top posts you want back"
        )
        postCount!: number;
    

【讨论】:

【参考方案3】:

我想这可以更多地被视为参考,因为在寻找 Swagger/OpenAPI 的说明时会出现这篇文章。

我已经设置了一个示例 repo,它显示了基本用法。 你可以在这里找到它:https://gitlab.com/WaldemarLehner/nestjs-swagger-example

缺少摘要

使用@ApiOperation-Decorator 定义端点描述。

@ApiOperation(description: "This is the main Description of an Endpoint.")

想要手动添加请求架构

首先,请注意您有一个 GET-Endpoint。因此,针对该端点的任何请求都不能有请求正文

所以.. 假设您使用允许请求正文(如 POST)的 HTTP 方法,您可以使用 @ApiBody-Decorator。

您可以在此处定义 Body-Summary、Schema(使用 OpenAPI-Schema Object)或 Type(Schema 是从 Class 及其装饰器中推断出来的)。

@ApiBody(
    type: PostHelloBodyDTO,
    description: "The Description for the Post Body. Please look into the DTO. You will see the @ApiOptionalProperty used to define the Schema.",
    examples: 
        a: 
            summary: "Empty Body",
            description: "Description for when an empty body is used",
            value:  as PostHelloBodyDTO
        ,
        b: 
            summary: "Hello Body",
            description: "Hello is used as the greeting",
            value: greeting: "Hello" as PostHelloBodyDTO
        
    
)

进一步参考

使用以下装饰将产生如下所示的 Swagger-Document。

@ApiOperation(description: "This is the main Description of an Endpoint.")
/// Request Documentation
@ApiParam(
    name: "name",
    description: "This Decorator specifies the documentation for a specific Parameter, in this case the <b>name</b> Param.",
    allowEmptyValue: false,
    examples: 
        a: 
            summary: "Name is Pete",
            description: "Pete can be provided as a name. See how it becomes a selectable option in the dropdown",
            value: "Pete"
        ,
        b: 
            summary: "Name is Joe",
            value: "Joe"
        
    
)
@ApiQuery(
    name: "useExclamation",
    description: "This is the description of a query argument. In this instance, we have a boolean value.",
    type: Boolean,
    required: false // This value is optional
)
@ApiBody(
    type: PostHelloBodyDTO,
    description: "The Description for the Post Body. Please look into the DTO. You will see the @ApiOptionalProperty used to define the Schema.",
    examples: 
        a: 
            summary: "Empty Body",
            description: "Description for when an empty body is used",
            value:  as PostHelloBodyDTO
        ,
        b: 
            summary: "Hello Body",
            description: "Hello is used as the greeting",
            value: greeting: "Hello" as PostHelloBodyDTO
        
    

)
/// Response Documentation
@ApiOkResponse(
    description: "This description defines when a 200 (OK) is returned. For @Get-Annotated Endpoints this is always present. When, for example, using a @Post-Endpoint, a 201 Created is always present",
    schema: 
        type: "string",
        example: "Hello, Pete!"
        // For instructions on how to set a Schema, please refer to https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.0.3.md#schema-object-examples
    
)
@ApiBadRequestResponse(
    description: "This description is for a 400 response. It is returned when additional query params are passed, or when the <b>useExclamation</b>-Argument could not be parsed as a boolean."
)
@ApiResponse(
    status: 417,
    description: "One can also provided a Status-Code directly, as seen here"
)
@Post(":name")
public postHello(...)...

结果

【讨论】:

以上是关于如何在 swagger nestjs 中手动添加摘要和正文的主要内容,如果未能解决你的问题,请参考以下文章

如何在nestjs中禁用swagger进行生产

@nestjs/swagger:如何在没有 @ApiOkResponse 装饰器的情况下添加架构?

在 NestJS 中,我可以在控制器级别添加啥装饰器以向我的 Swagger 文档添加授权标头?

NRWL + NestJS 尝试使用 Swagger 插件

NestJS Swagger:在 ApiProperty 装饰器中描述地图

如何使用 nestjs/swagger 更改查询参数序列化?