[英]OpenApi arrays and nested objects validation
我正在使用 OpenApi 規范,這是生成 class 的代碼示例:
CreateUsersRequest:
required:
- userIds
type: object
properties:
userIds:
uniqueItems: true
minItems: 1
type: array
items:
type: string
format: uuid
我想禁止發送以下請求:
{
"userIds": [
""
]
}
{
"userIds": [
null
]
}
如果我使用javax.validation
它看起來像:
@NotNull
private List<@NotEmpty UUID> userIds;
有沒有辦法使用api.yml
文件來做同樣的事情?
如文檔中所示:
OpenAPI 3.0 沒有明確的
null
類型,如 JSON Schema 中那樣,但您可以使用nullable: true
來指定該值可能是null
。 請注意,null
與空字符串""
不同。
為了防止出現空字符串,您可以提供pattern
正則表達式。
請嘗試以下方法:
CreateUsersRequest:
required:
- userIds
type: object
properties:
userIds:
uniqueItems: true
minItems: 1
type: array
items:
type: string
format: uuid
nullable: false
pattern: ^[a-z|\-]+$
請仔細測試代碼,我意識到你使用了format: uuid
,所以我對format
和pattern
的組合沒有絕對的信心。
如有必要,您可以嘗試提供自己的uuid
類型。 例如:
Uuid:
type: string
pattern: '^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$'
nullable: false
和:
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.