Krish
Krish

Reputation: 4232

Compile time errors on Mule 4 DataWeave

I am new for Mulesoft Dataweave language and I am not understanding what mistake I am doing in below both code-1 and code-2 syntax. It is showing a compile time error on the if blocks. Can you please suggest what mistake am I doing in below scripts?

Code-1

%dw 2.0
fun createUserData(name) = { 
    if(name=="USA"){
        readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
    }else{
        readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
    }
}
output application/json
---
createUserData("USA")

code-2

output application/json
---
    if(payload != null){
            readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
    }else{
            readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
    }

enter image description here

enter image description here

Upvotes: 0

Views: 241

Answers (2)

aled
aled

Reputation: 25782

Your problem is not with the condition but the syntax for the object it returns. In DataWeave curly braces are not part of the if/else condition. The curly braces delimit an object, which contains key-value pairs. Your expression starts an object but misses the keys. Assuming the readUrl() returns an object { a: 1 } it would be equivalent to:

{ { a: 1} }

which is invalid because the outer object has no keys, only a value. In that case you could just return the result of readUrl() without the braces:

 if(payload != null)
            readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
    else
            readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
    

Since whatever inside each branch of the if/else are just more expressions you can transform them too.

See @Salim Khan's answer for more examples.

Upvotes: 3

Salim Khan
Salim Khan

Reputation: 4303

You can try with an approach like this

%dw 2.0
output application/json
fun createUserData(name) = { 
    a: if(name=="USA")
        readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
    else
        readUrl("https://jsonplaceholder.typicode.com/posts/1", "application/json")
  
}
---
createUserData("USA").a

Another sample script:

%dw 2.0
output application/json
var a  =  "1"
---
if (a == "1") ["a","b"] ++ ["c","d"] ++ [{"abc": "hello"}]
else if ( a == "2" or a == "3") {
      v: " this is ok"
}
else {
    v: "this is just ok"
}

Another sample:

%dw 2.0
import * from dw::util::Values
output application/json
var a  =  "1"
var b = {"hello" : "world"}
---
if (a == "1") ["a","b"] ++ ["c","d"] ++ [{"abc": "hello"}] + (b update "hello" with "hello")
else if ( a == "2" or a == "3") {
      v: " this is ok"
}
else {
    v: "this is just ok"
}

Upvotes: 3

Related Questions