Dynamically Evaluate Dataweave Scripts
This article demonstrates how to use Dynamic Evaluate Component in Mule 4 to execute dataweave scripts dynamically.
Join the DZone community and get the full member experience.
Join For FreeThis article demonstrates how to use Dynamic Evaluate Component in Mule 4 to execute dataweave scripts dynamically.
It is a very common use case where a developer may have to execute different dwl scripts (account.dwl/customer.dwl in this case) depending on the input parameter.
dw/customer.dwl:
x
{
"customer":{
"id":payload.customerId,
"name": payload.customerName,
"address": payload.customerAddress,
"mobile": payload.customerMobile,
"accountId": payload.customerAccountId,
"category": payload.customerCategory
}
}
dw/account.dwl:
x
{
"account":{
"id": payload.accountId,
"name": payload.accountName,
"address": payload.accountAddress,
"customerId": payload.accountOwnerId,
"startDate": payload.accountStartDate,
"renewalDate": payload.accountRenewalDate,
"subscriptionType": payload.accountSubscription
}
}
The First thing that will hit our mind is a Choice router. But is it an optimized way? What if in the future we may have more objects? We will have to update the code if we use a choice router.
But using Dynamic Component Evaluator or dataweave custom module we can avoid it.
Using Dynamic Component Evaluator
Below are the steps:
Create a dwl file that sets the script name in a variable based on the input parameter.
xxxxxxxxxx
<ee:transform>
<ee:variables ><ee:set-variable variableName="script" >
<![CDATA[
%dw 2.0
output application/java
var fileName= "dw/$(vars.inputParameter).dwl"
---
readUrl("classpath://" ++ fileName,"text/plain")
]]>
</ee:set-variable> </ee:variables>
</ee:transform>
This step should give you the dwl file full path in the script variable. Eg. dw/account.dwl or dw/customer.dwl.
- Use the script variable in the Dynamic Evaluate Component
<ee:dynamic-evaluate doc:name="Dynamic Evaluate"
expression="#[vars.script]"/>
In the future, if we have more objects then add the <object>.dwl file in the resource/dw folder.
Sample flow:
Using Dataweave Custom Module
Below are the steps:
1. Define a custom module for customer and account object. Refer below code snippet:
xxxxxxxxxx
%dw 2.0
var account = (acc: Object) -> {
account: {
id: acc.accountId,
name: acc.accountName,
address: acc.accountAddress,
customerId: acc.accountOwnerId,
startDate: acc.accountStartDate,
renewalDate: acc.accountRenewalDate,
subscriptionType: acc.accountSubscription
}
}
2. Import the modules in the transform message component and invoke the function we created:
xxxxxxxxxx
%dw 2.0
output application/json
import dw::account as Acc
import dw::customer as Cust
---
if (vars.inputParameter == "customer") Cust::customer(payload) else Acc::account(payload)
Happy coding!
Opinions expressed by DZone contributors are their own.
Comments