我有我的控制器
@Post('email/register')
@HttpCode(HttpStatus.CREATED)
@ApiOkResponse(AuthConfigSwagger.API_OP_CREATE)
@ApiCreatedResponse(AuthConfigSwagger.API_RES_CREATE)
async register(@Body() authRegisterLoginDto: AuthRegisterLoginDto) {
return this.authService.register(authRegisterLoginDto);
}
哪里
AuthConfigSwagger.API_RES_CREATE
是
static readonly API_RES_CREATE: ApiResponseOptions = {
description: 'The user has been successfully created.',
type: User
};
该响应不是我创建的真实响应。 这样,我就显示了整个文档(我正在使用 mongoDb)
我需要输入我的自定义回复,例如
{
"statusCode": 201,
"message": "",
"status": "success"
}
有时我需要使用用户属性。
我阅读了文档,但找不到任何自定义响应的属性。
更新:
我可以创建一个类:
import { ApiProperty } from "@nestjs/swagger";
export class successResponse {
@ApiProperty({
example: 'success',
description: 'status',
})
status: string;
@ApiProperty({
description: 'status',
})
message?: string;
@ApiProperty({
description: 'could contain some info',
})
data?: object;
}
我有
{
"status": "success",
"message": "string",
"data": {}
}
在我关于招摇的示例中。但是,例如在登录路由中,我希望在 200 Response 上看到类似的内容:
{
"data": {
"expiresIn": number,
"accessToken": "string",
"user": {
"name": "string",
"email": "string",
"id": "string"
}
},
"statusCode": number,
"status": "string"
}
我不想为每个 API 创建自定义响应。
例如使用接口。
interface IResponseWrapper<T>{
status: string;
statusCode: number;
data: T
}
现在使用这个接口来扩展你的类
创建“successResponse”类后,您需要将其包含在 @ApiResponse() 装饰器中。在“类型”选项里面
此外,我将类名从 “successResponse” 更改为 “SucessResponse”。它使区分类和方法变得更容易。
@Post('email/register')
@HttpCode(HttpStatus.CREATED)
@ApiOkResponse(AuthConfigSwagger.API_OP_CREATE)
@ApiResponse({type: SuccessResponse})
@ApiCreatedResponse(AuthConfigSwagger.API_RES_CREATE)
async register(@Body() authRegisterLoginDto: AuthRegisterLoginDto) {
return this.authService.register(authRegisterLoginDto);
}
这将使 swagger 知道该端点的响应类型。
此外,您可能想创建一些额外的类来查看您想要的所有字段。
import { ApiProperty } from "@nestjs/swagger";
export class UserData{
@ApiProperty()
name: string
@ApiProperty()
email: string
@ApiProperty()
id: string
}
export class DataResponse {
@ApiProperty()
expiresIn: number,
@ApiProperty()
accessToken: "string",
@ApiProperty({type: UserData})
user: UserData
}
export class SuccessResponse {
@ApiProperty({
example: 'success',
description: 'status',
})
status: string;
@ApiProperty({
description: 'status',
})
message?: string;
@ApiProperty({
description: 'could contain some info',
type: DataResponse
})
data?: DataResponse;
}
然后像这样添加到端点
@Post('email/register')
@HttpCode(HttpStatus.CREATED)
@ApiOkResponse(AuthConfigSwagger.API_OP_CREATE)
@ApiResponse({type: SuccessResponse})
@ApiCreatedResponse(AuthConfigSwagger.API_RES_CREATE)
async register(@Body() authRegisterLoginDto: AuthRegisterLoginDto) {
return this.authService.register(authRegisterLoginDto);
}