mule - 如何在数据编织中的有效负载中为多个键的值为空的有效负载添加错误?
问题描述
我有一个有效负载,我需要检查一些特定的验证,如果验证不成功,我想向有效负载中的新数组添加一个错误。
输入 :
[
{
"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": ""
}
}
]
即使我可以从上面的输出中找出哪个对象中有错误,这也将达到目的。
如何使用Errors
array with获得上面显示的所需输出{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": "",
"Errors": {
"Error": true,
"Error Message": "Invoice is null or empty"
}
}
]
推荐阅读
- python - Django Reset PW 电子邮件不在 AWS 上发送
- c++ - 拦截 V8 中的任何传出网络请求(在核心级别)
- javascript - 单击按钮时,如何阻止我的 HTML 表格丢失其数据?
- mergesort - 如何仅使用合并排序算法对奇数列表进行排序?还有偶数分开吗?
- javascript - Dart:将 html 文件加载到 Flutter Webview 中
- javascript - jquery .ajax 从同一页面上的两个表单提交数据
- java - 用另一个 ArrayList 的所有元素创建一个新的 ArrayList,除了一行代码
- r - 基于“开始和停止”字符串的子集行
- python - 读取文本文件并删除 Python 中除字母和空格以外的所有字符
- sql - 根据来自单独表的选择查询从另一个表添加列