首页 > 解决方案 > Swagger Nest.js ValidationPipe ApiBadRequestResponse

问题描述

我刚开始玩 Swagger,一切都很棒。我能够在一个小时左右的时间内记录所有 API,但我在解决最后一个问题时遇到了困难。

如何告诉 swagger 以ApiBadRequestResponse下面的格式显示?

@ApiOkResponse({
  type: User,
})
@ApiBadRequestResponse({
  type: {
    error: String,
    message: ValidationError[]
  }
})
@Post('/signup')
signUp(
  @Body(ValidationPipe) authCredentialsDto: CredentialsDTO
): Promise<User> {
  return this.userService.signUp(authCredentialsDto)
}

据我了解,swagger 不知道如何使用接口,而我必须使用类。有没有一种简单的方法来记录由ValidationPipe. 这都是本机@nestjs行为,所以我认为必须有一个简单的解决方案。

这是从 API 实际返回的内容:

"statusCode": 400,
"error": "Bad Request",
"message": [
  {
    "target": {
      "username": "somename",
      "password": "****"
    },
    "value": "****",
    "property": "password",
    "children": [], // ValidationError[]
    "constraints": {
      "matches": "password too weak"
    }
  }
]

标签: node.jstypescriptswaggerdocumentationnestjs

解决方案


推荐阅读