首页 > 解决方案 > 如何在数据编织中的有效负载中为多个键的值为空的有效负载添加错误?

问题描述

我有一个有效负载,我需要检查一些特定的验证,如果验证不成功,我想向有效负载中的新数组添加一个错误。

输入 :

[
  {
    "order": "123",
    "product": "",
    "invoice": "Lock"
    },
   {
    "order": "123",
    "product": "456",
    "invoice": ""
    }
    ]

在上面的输入中,我需要检查 Invoice == 'Locked' 和 Product != null,需要根据不同的 json 数组检查订单以查看该值是否存在,但我只想了解有关发票和产品的想法获得不同的验证并将错误添加到错误数组..

预期输出应该是:

[
  {
    "order": "123",
    "product": "",
    "invoice": "Lock",
    "Errors" : {
      "Error" : true,
      "Error Message" : "Invoice is not "Locked", product is null"
      }
    },
   {
    "order": "123",
    "product": "456",
    "invoice": "123",
    "Errors" : {
      "Error" : false,
      "Error Message" : ""
      }
    }
    ]

我希望能够检查不同键的不同验证。

我能够实现以下输出,其中我为每个单独的键使用不同的功能并为每个键添加错误,但是过滤出发生了哪个错误变得非常具有挑战性?

[
  {
    "order": "123",
    "product": "",
    "invoice": "",
    "Errors": {
      "Order ": "Order is NULL,",
      "Product": "",
      "Invoice": ""
      }
    },
   {
    "order": "123",
    "product": "456",
    "invoice": "123",
    "Errors": {
      "Order ": "",
      "Product": "",
      "Invoice": ""
      }
    }
    ]

即使我可以从上面的输出中找出哪个对象中有错误,这也将达到目的。

如何使用Errorsarray with获得上面显示的所需输出{Error, error message}

标签: mulemule-studiodataweavemule-componentmulesoft

解决方案


您可以尝试使用以下 DataWeave 表达式:

%dw 2.0
output application/json

fun addMessage(condition, message) = if (condition) message else null

fun validate(item) = 
    []
    << addMessage(isEmpty(item.order), "Order is null or empty")
    << addMessage(isEmpty(item.product), "Product is null or empty")
    << addMessage(isEmpty(item.invoice), "Invoice is null or empty")
    << addMessage(item.invoice ~= "Lock", "Invoice is locked")
    // keep adding other validation here

fun addError(messages) =
   {
       "Errors" : {
            "Error": !isEmpty(messages),
            "Error Message": ((messages filter (item) -> (item != null)) as Array) joinBy ", "
       }
   }

---
payload map (item, index) -> 
    item 
    ++  addError(validate(item))

它将根据提供的示例有效负载生成以下输出:

[
  {
    "order": "123",
    "product": "",
    "invoice": "Lock",
    "Errors": {
      "Error": true,
      "Error Message": "Product is null or empty, Invoice is locked"
    }
  },
  {
    "order": "123",
    "product": "456",
    "invoice": "",
    "Errors": {
      "Error": true,
      "Error Message": "Invoice is null or empty"
    }
  }
]

推荐阅读