简体   繁体   English

OpenApi arrays 和嵌套对象验证

[英]OpenApi arrays and nested objects validation

I'm using OpenApi specification, this is an example of code that generates the class:我正在使用 OpenApi 规范,这是生成 class 的代码示例:

CreateUsersRequest:
      required:
        - userIds
      type: object
      properties:
        userIds:
          uniqueItems: true
          minItems: 1
          type: array
          items:
            type: string
            format: uuid

I want to prohibit sending the following request:我想禁止发送以下请求:

{
  "userIds": [
    ""
  ]
}
{
  "userIds": [
    null
  ]
}

In case I used javax.validation it would look like:如果我使用javax.validation它看起来像:

@NotNull 
private List<@NotEmpty UUID> userIds;

Is there any ways to do the same using api.yml file?有没有办法使用api.yml文件来做同样的事情?

As indicated in the documentation :文档中所示:

OpenAPI 3.0 does not have an explicit null type as in JSON Schema, but you can use nullable: true to specify that the value may be null . OpenAPI 3.0 没有明确的null类型,如 JSON Schema 中那样,但您可以使用nullable: true来指定该值可能是null Note that null is different from an empty string "" .请注意, null与空字符串""不同。

To prevent the empty string you could provide a pattern regex.为了防止出现空字符串,您可以提供pattern正则表达式。

Please, try the following:请尝试以下方法:

CreateUsersRequest:
      required:
        - userIds
      type: object
      properties:
        userIds:
          uniqueItems: true
          minItems: 1
          type: array
          items:
            type: string
            format: uuid
            nullable: false
            pattern: ^[a-z|\-]+$

Please, test the code carefully, I realized you used format: uuid , so I am not absolutely confident about the combination of format and pattern .请仔细测试代码,我意识到你使用了format: uuid ,所以我对formatpattern的组合没有绝对的信心。

If necessary, you could try providing your own uuid type.如有必要,您可以尝试提供自己的uuid类型。 For example:例如:

Uuid:
    type: string
    pattern: '^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$'
    nullable: false

And:和:

CreateUsersRequest:
      required:
        - userIds
      type: object
      properties:
        userIds:
          uniqueItems: true
          minItems: 1
          type: array
          items:
            $ref: "#/components/schemas/Uuid"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM