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

Comments

Post a Comment

Popular posts from this blog

XML Schema and JSON Schema Validation in Mule 4

Using XML To Java in TIBCO BW

Parsing a JSON String and Converting it to XML in TIBCO