如何在dataweave中的payload中为多个键的值为null的payload添加错误?

问题描述

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

输入:

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

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

预期输出应该是:

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

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

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

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

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

如何使用 Errors 数组和 {Error,error message} 获得上面显示的所需输出

解决方法

您可以尝试使用以下 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": "","Error Message": "Invoice is null or empty"
    }
  }
]
,

你可以试试这个脚本 -

tools:replace="android:allowBackup" 
android:allowBackup="true" 

它将产生如下输出 -

%dw 2.0
output application/json
import someEntry from dw::core::Objects
fun maperror(item) = do {
    var error =  item someEntry (value,key) -> isEmpty(value)
    ---
    {
    "Error" : error,"Error Message" : if (error) keysOf((item filterObject ((value,key,index) -> isEmpty(value)))) map ($ ++ " is null") joinBy "," else ""
    }
}
---
payload map {
    ($),"Errors": maperror($)
}