gpt4 book ai didi

javascript - Joi验证: How to make values in nested json optional?

转载 作者:行者123 更新时间:2023-12-03 02:01:34 25 4
gpt4 key购买 nike

所以我有一个类似于下面的嵌套 json,它是我正在编写的 api 的有效负载结构

{"item_id":"1245",
"item_name":"asdffd",
"item_Code":"1244",
"attributes":[{"id":"it1","value":"1"},{"id":"it2","value":"1"}],
"itemUUID":"03741a30-3d62-11e8-b68b-17ec7a13337"}

我对有效负载的 Joi 验证是:

validate: {
payload: Joi.object({
item_id: Joi.string().required(),
item_name: Joi.string().required(),
placeId: Joi.string().allow('').allow(null),
itemUUID: Joi.string().allow('').allow(null),
item_Code: Joi.string().required().allow(null),
attributes: Joi.alternatives().try(attributeObjectSchema, attributesArraySchema).optional()
})
}

哪里

const attributeObjectSchema = Joi.object({
id: Joi.string().optional(),
value: Joi.string().optional()
}).optional();

const attributeArraySchema = Joi.array().items(customAttributeObjectSchema).optional();

我的问题是:通过上述 Joi 验证,如果我编辑有效负载并发送如下所示的属性标签(即“值”为空)

"attributes":[{"id":"CA1","value":""},{"id":"CA2","value":""}]

它抛出一个错误:

"message": "child \"attributes\" fails because [\"attributes\" must be an object, \"attributes\" at position 0 fails because [child \"value\" fails because [\"value\" is not allowed to be empty]]]",
"validation": {
"source": "payload",
"keys": [
"attributes",
"attributes.0.value"
]

我在这里做错了什么?如果我需要 Joi 接受以下内容,我需要做什么:

 "attributes":[{"id":"CA1","value":""},{"id":"CA2","value":""}]

最佳答案

做这样的事情

attributeArraySchema.customAttributes = [];
attributeArraySchema.customAttributes = [
{"id":"CA1","value":""},
{"id":"CA2","value":""}
];

关于javascript - Joi验证: How to make values in nested json optional?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49991772/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com