Global Function that can be used in Mule DataWeave
You can write a Groovy custom function that can be used in Mule DataWeave (Transform Message). To do this, create a file with .mvel extension under src/main/resources, e.g. globalfunction.mvel.
If you're familiar with Java, it is quite similar to Groovy, but with some differences such as type declaration is not required in Groovy and a statement doesn't have to be punctuated with a semi-colon as long as you write one statement per line.
For example, we have the following Groovy function, which accepts a MongoDB ObjectId and converts it into a string value. This is useful when you just need to get the hexadecimal value and not the object itself, which gets serialized when transforming to JSON.
def getObjectIdAsString(objectId) {
return ((org.bson.types.ObjectId) objectId).toString()
}
In the Mule configuration file, add the below XML. You don't need to specify the complete path since src/main/resources automatically gets added to the classpath.
<configuration doc:name="Global_Function">
<expression-language>
<global-functions file="globalfunction.mvel"></global-functions>
</expression-language>
</configuration>
Use the function directly in your DataWeave script.
%dw 1.0
%output application/json
---
payload map
{
"id": getObjectIdAsString($."_id")
}
If you're familiar with Java, it is quite similar to Groovy, but with some differences such as type declaration is not required in Groovy and a statement doesn't have to be punctuated with a semi-colon as long as you write one statement per line.
For example, we have the following Groovy function, which accepts a MongoDB ObjectId and converts it into a string value. This is useful when you just need to get the hexadecimal value and not the object itself, which gets serialized when transforming to JSON.
def getObjectIdAsString(objectId) {
return ((org.bson.types.ObjectId) objectId).toString()
}
In the Mule configuration file, add the below XML. You don't need to specify the complete path since src/main/resources automatically gets added to the classpath.
<configuration doc:name="Global_Function">
<expression-language>
<global-functions file="globalfunction.mvel"></global-functions>
</expression-language>
</configuration>
Use the function directly in your DataWeave script.
%dw 1.0
%output application/json
---
payload map
{
"id": getObjectIdAsString($."_id")
}
Thank for sharing useful post with us.
ReplyDeleteMulesoft Online Training
Mulesoft Training in Hyderabad
thanks for sharing most valuable information.
ReplyDeleteMulesoft Online Training india
Mulesoft Online Training in Hyderabad
I have found great and massive information on. Thanks for sharing
ReplyDeleteMulesoft Training in Hyderabad
Mulesoft Onine Training Hyderabad