Warm tip: This article is reproduced from serverfault.com, please click

Complex operations in dataweave

发布于 2020-12-16 09:23:32

I need to map a groovy code into dataweave. The existing groovy code is similar to the pseudo example as-

if(condition) {
  payload.each { data -> {
     function1(data.attributes)
     function2(data.attributes)
     if(condition) {set flag}
  }
  if(flag is set) {return payload}
  else {return errorMessage}
}
}

function1(data) {if(condition) {return errorMessage} else {return data}}
function2(data) {if(condition) {return errorMessage} else {return data}}

Consider the input payload as-

[
{
  "attribute1": "value1",
  "attribute2": "value2",
  "attribute3": "value3",
  "attribute4": "value4",
},
{
  "attribute1": "value5",
  "attribute2": "value6",
  "attribute3": "value7",
  "attribute4": "value8",
}
]

The output is an JSON array, which is dependent on the flag variable. If the flag is set, output JSON array will be about the errorMessages else pass the original payload. Is there a way in which this can be converted into a dataweave without using much additional mule processes?

Thanks in advance

Questioner
Satyam Pisal
Viewed
0
olamiral 2020-12-16 18:53:48

Supposing you have a variable called flag (true meaning success and false meaning error) and a variable containing the error message, you can use the following DataWeave expression:

%dw 2.0
output application/json
---
if (vars.flag == true) 
  payload 
else 
{
  errorMessage: vars.errorMessage
}

If the value of vars.flag is true, the DataWeave expression will return the payload as it is. Otherwise, it will return a JSON object similar to:

{
  "errorMessage": "An error occurred" 
}