Как добавить резюме и тело вручную в Swagger nestjs

Я пытаюсь добавить резюме в свои маршруты документации 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);
  }

4 ответа

Решение

Для сводки конечной точки вы можете использовать @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

Я предполагаю, что это можно рассматривать скорее как ссылку, поскольку этот пост появляется при поиске инструкций для Swagger/OpenAPI.

Я создал пример репо, который показывает основное использование. Вы можете найти его здесь: https://gitlab.com/WaldemarLehner/nestjs-swagger-example

Отсутствует сводка

Использовать @ApiOperation-Decorator для определения Endpoint-Description.

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

Хотите вручную добавить схему запроса

Прежде всего, обратите внимание, что у вас есть GET-Endpoint. В результате любой запрос к этой конечной точке не может иметь тело запроса .

Итак... предполагая, что вы используете HTTP-метод, который допускает тело запроса (например, POST), вы можете использовать @ApiBody-Декоратор.

Здесь вы можете определить Body-Summary, Schema (используя объект OpenAPI-Schema Object) или тип (Schema выводится из класса и его декораторов).

      @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, как показано ниже.

      @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(...){...}

Результат

Я бы предложил создать DTO для всех ваших конечных точек (resp и req).

Вот как бы вы добавили сводку к схеме (на скриншоте щелкните "схема" в области, обведенной красным) с помощью декоратора DTOs + @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;
}

Если кто-то ищет решение в новой версии Quarkus/OpenAPI, то вот решение:

  1. Добавляем тело запроса:
       @RequestBody(content = @Content(
            examples = {@ExampleObject(name = "Testing Name", value = "{'name':'Abc', 'age':23}", description = "Testing Description")}))
  1. Добавление резюме:
      @Operation(summary = "Testing GitHub File Reader")

Вместе:

      import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.media.Content;
import org.eclipse.microprofile.openapi.annotations.media.ExampleObject;
import org.eclipse.microprofile.openapi.annotations.parameters.RequestBody;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.Map;

@Path("/api")
public class RestControllerResponse {

    @Path("/generate")
    @POST
    @Operation(summary = "Testing GitHub File Reader")
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @RequestBody(content = @Content(
            examples = {@ExampleObject(name = "Testing Name", value = "{'name':'Abc', 'age':23}", description = "Testing Description")}))
    public String generator(final Map<String, Object> input) throws Exception {
        return "Hello From Generator Method";
    }
}
Другие вопросы по тегам