简体   繁体   中英

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"
}

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM