【问题标题】:Joi Validation: How to make values in nested json optional?Joi 验证:如何使嵌套 json 中的值可选?
【发布时间】:2018-10-04 03:07:25
【问题描述】:

所以我有一个类似下面的嵌套 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":""}]

【问题讨论】:

    标签: javascript json nested joi


    【解决方案1】:

    做这样的事情

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

    【讨论】:

    • 首先声明一个带有空白数组的键,然后分配该键数据最简单的方法来在对象中添加自定义键
    【解决方案2】:

    所以我通过从

    更改以下架构定义来解决这个问题
    const attributeObjectSchema = Joi.object({
        id: Joi.string().optional(),
        value: Joi.string().optional()
    }).optional();
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-30
      • 2018-02-27
      • 2019-03-23
      • 1970-01-01
      • 2020-02-21
      • 2015-10-17
      • 2021-04-15
      • 2019-10-15
      相关资源
      最近更新 更多