Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic function call in mule 4

I have multiple functions:

fun testadd(payload) = 
({
addition: payload.value1 as Number + payload.value2 as Number
})

fun testsub(payload) = 
({
substraction: payload.value1 as Number - payload.value2 as Number
})

fun testmultiply(payload) = 
({
multiplication: payload.value1 as Number * payload.value2 as Number
})

I want to call the function dynamically based on the value of "Operation" property/element. suppose if "Operation" = "testadd" then call testadd function, if "Operation" = "testsub" then call testsub function

Input :

{
"value1" : 10,
"value2" : 20,
"Operation" : "testadd"
}
like image 845
Kunal Awasthi Avatar asked Aug 31 '26 14:08

Kunal Awasthi


2 Answers

An alternative here is to use function overloading and literal types. For example:

%dw 2.0
output json

fun binOp(a, b, op : "add") = a + b
fun binOp(a, b, op : "sub") = a - b
fun binOp(a, b, op : "mul") = a * b
---
binOp(10, 20, "add")

DataWeave will call the correct function based on the value of the op parameter.

like image 58
afelisatti Avatar answered Sep 03 '26 05:09

afelisatti


Since functions in DataWeave are named lambdas you can could just convert them to lambdas, assign them as values of an object and use the keys as the names.

Example:

%dw 2.0
output application/json
var functions={
    testadd: (payload) -> {
        addition: payload.value1 as Number + payload.value2 as Number
    },
    testsub: (payload) -> {
        substraction: payload.value1 as Number - payload.value2 as Number
    }
}
---
functions[payload.Operation](payload)

Output (for the input in the question):

{
  "addition": 30
}

Alternatively you could have the functions as functions and just reference them by name in the object:

%dw 2.0
output application/json

fun testadd(payload) = {
    addition: payload.value1 as Number + payload.value2 as Number
}

fun testsub(payload) = {
    substraction: payload.value1 as Number - payload.value2 as Number
}

var functions={
    testadd: testadd,
    testsub: testsub
}
---
functions[payload.Operation](payload)
like image 43
aled Avatar answered Sep 03 '26 05:09

aled



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!