如何在 NestJs 生成的 Swagger 文档中定义响应主体对象?
How to define the response body object, in a NestJs-generated Swagger document?
我正在使用 NestJs 及其 Swagger 插件自动生成我的 API 的文档。
问题是,我不知道如何使 response 模式出现在文档中。在我的 GET 路由中,我得到的只是“代码 200”,没有数据结构。
我有一个典型的设置,其中控制器方法使用相应的服务方法,而服务方法又使用 TypeOrm 存储库。例如:
@Get()
findAll() {
return this.usersService.findAll();
}
我尝试使用 @ApiResponse 装饰器,但没有真正看到任何方法可以让它达到这个目的。此外,创建 user.dto.ts 并使其成为控制器路由的 return 类型没有任何好处。
最终,这就是我在 Swagger 中得到的结果:
如何定义响应正文架构?
您可以将 type
和 isArray
属性与 ApiResponse
系列装饰器结合使用。例如:
@ApiOkResponse({
description: 'The user records',
type: User,
isArray: true
})
@Get()
findAll() {
return this.usersService.findAll();
}
此外,考虑使用 Swagger CLI plugin 来帮助您在构建期间自动应用这些装饰器,而不必手动保持所有内容同步。
您可以使用 ApiExtraModels
注释控制器操作:
import { ApiExtraModels, ApiResponse, getSchemaPath } from '@nestjs/swagger'
import { Controller, Get, Param } from '@nestjs/common';
@Controller('users')
export class UsersController {
@ApiExtraModels(UserDto)
@ApiResponse({
status: 200,
schema: {
$ref: getSchemaPath(OrderDto),
},
})
@Get('/:userId')
getById(@Param('userId') userId: string): UserDto {
... something happens ...
return myUserDto;
}
}
并且您还必须使用 ApiProperty
:
注释 UserDto
属性
import { ApiProperty } from '@nestjs/swagger'
import { Expose } from 'class-transformer'
import { IsString } from 'class-validator'
export class UserDto {
@ApiProperty()
@IsString()
@Expose()
id: string;
}
顺便说一下,检查一下 CLI plugin for generating ApiProperty
我正在使用 NestJs 及其 Swagger 插件自动生成我的 API 的文档。
问题是,我不知道如何使 response 模式出现在文档中。在我的 GET 路由中,我得到的只是“代码 200”,没有数据结构。
我有一个典型的设置,其中控制器方法使用相应的服务方法,而服务方法又使用 TypeOrm 存储库。例如:
@Get()
findAll() {
return this.usersService.findAll();
}
我尝试使用 @ApiResponse 装饰器,但没有真正看到任何方法可以让它达到这个目的。此外,创建 user.dto.ts 并使其成为控制器路由的 return 类型没有任何好处。
最终,这就是我在 Swagger 中得到的结果:
如何定义响应正文架构?
您可以将 type
和 isArray
属性与 ApiResponse
系列装饰器结合使用。例如:
@ApiOkResponse({
description: 'The user records',
type: User,
isArray: true
})
@Get()
findAll() {
return this.usersService.findAll();
}
此外,考虑使用 Swagger CLI plugin 来帮助您在构建期间自动应用这些装饰器,而不必手动保持所有内容同步。
您可以使用 ApiExtraModels
注释控制器操作:
import { ApiExtraModels, ApiResponse, getSchemaPath } from '@nestjs/swagger'
import { Controller, Get, Param } from '@nestjs/common';
@Controller('users')
export class UsersController {
@ApiExtraModels(UserDto)
@ApiResponse({
status: 200,
schema: {
$ref: getSchemaPath(OrderDto),
},
})
@Get('/:userId')
getById(@Param('userId') userId: string): UserDto {
... something happens ...
return myUserDto;
}
}
并且您还必须使用 ApiProperty
:
UserDto
属性
import { ApiProperty } from '@nestjs/swagger'
import { Expose } from 'class-transformer'
import { IsString } from 'class-validator'
export class UserDto {
@ApiProperty()
@IsString()
@Expose()
id: string;
}
顺便说一下,检查一下 CLI plugin for generating ApiProperty