1

我需要创建一个具有以下伪代码条件的函数:

var consent = []

function buildConsent() {
   if (condition1) {
       consent += values1
   }

   if (condition2) {
       consent += values2
   }

   if (condition3) {
       consent += values3
   }
}

这就是我在 Mule4 和 DW 2.0 上的做法:

%dw 2.0
var consent = []
var factIntake = vars.facts

fun buildConsent() =
    if (factIntake.miscFactItems[?($.value1 == true)] != null) {
        consent + {
            "Consent_Type": "some1",
            "Consent_Given_By": "some2"
        }
    }

    if (factIntake.miscFactItems[?($.value2 == true)] != null) {
        consent + {
            "Consent_Type": "some3",
            "Consent_Given_By": "some4"
        }
    }

output application/json
--
{
    "Consent_Data": buildConsent()
}

但我从 IDE (AnypointStudio 7) 收到以下错误:

无效的输入“+”,预期的命名空间或属性<'@('(Name:Value)+')'>(第 11 行,第 11 列):

其中第 11 行第 11 列是consent +. 如果我尝试调试项目,我在控制台中得到的只是:

消息:解析脚本时出错:%dw 2.0

这是一个输入/输出示例,让您更好地理解我想要实现的目标:

// Input
{
    "miscFactItems": [{
            "factId": "designeeFirstName",
            "factValue": "test test",
            "factValueType": "System.String"
        }, {
            "factId": "designeeLastName",
            "factValue": "test test",
            "factValueType": "System.String"
        },{
            "factId": "value1",
            "factValue": true,
            "factValueType": "System.Boolean"
        }, {
            "factId": "value2",
            "factValue": true,
            "factValueType": "System.Boolean"
        }, {
            "factId": "value3",
            "factValue": true,
            "factValueType": "System.Boolean"
        }
    ]
}

// Output
consent = [{
             "Consent_Type": "type1",
             "Consent_Given_By": miscFactItems.designeeFirstName
         }, {
             "Consent_Type": "type2",
             "Consent_Given_By": miscFactItems.designeeFirstName
         }, {
             "Consent_Type": "type3",
             "Consent_Given_By": miscFactItems.designeeFirstName
         }
]

我在这里缺少什么?如何将三个条件添加到我的函数并将值附加到consentvar?

4

2 回答 2

2

在 DataWeave 中变量是不可变的,所以你不能在同一个变量中累积东西,你需要创建新的变量。

所以它看起来像这样:

%dw 2.0
output application/json  

var consent1 = if (condition1) [{"Consent_Type": "some1", "Consent_Given_By": "some2"}] else []
var consent2 = if (condition2) [{"Consent_Type": "some3", "Consent_Given_By": "some4"}] else []
---
consent1 ++ consent2
于 2019-06-04T18:54:57.117 回答
0

您的要求看起来像是对reduce功能的良好使用。根据您提供的伪代码,您可以执行以下操作

output application/json
var payload = [  
    {"name":"Ram", "email":"Ram@gmail.com", "state": "CA","age":21},  
    {"name":"Bob", "email":"bob32@gmail.com","state": "CA","age":30},
    {"name":"john", "email":"bob32@gmail.com","state": "NY","age":43} 

] 
---
payload reduce ((item, consent = []) -> consent +
{
    (state: item.state) if(item.state=='CA'),
    (age: item.age) if(item.age >25)
}
)
于 2019-05-30T16:08:52.180 回答