Mule 4: Dataweave 2 In Action: Use Function Modules
In this article, I am going to present Mule 4 ways to define and use global functions.
Join the DZone community and get the full member experience.
Join For FreeIn Mule 4, the mel2 functionalities are replaced by the Dataweave 2 ones. For those who worked in Mule 3, you will find the Mule 4 ways of using function modules are much more advanced than the old way (see my post). In this article, I am going to present Mule 4 ways to define and use global functions.
Here is my project layout:
As you can see, I place the function modules in the dir: src/main/resources/modules. And the Dataweave function module is defined in CommonFunc.dwl.
%dw 2.0
fun concatName(aPerson) = aPerson.firstName ++ ' ' ++ aPerson.lastName
fun stringToDateUTC(dateString) = ((dateString as String {format: "yyyy-MM-dd'T'HH:mm:ss.SSSZ"} >> "UTC"
)) as DateTime {format: "yyyy-MM-dd'T'HH:mm:ss.SSS"}
I defined two functions: concatName, stringToDateUTC. The purposes are self-explained.
I place the normal Dataweave modules in the dir of src/main/resources/dataweave. The usage of the functions is demonstrated at the following dwl file:
%dw 2.0
import * from modules::CommonFunc
output application/json
---
{
"Name" : concatName(payload),
"CreatedDate" : stringToDateUTC(payload.createdDate)
}
Here are few points:
- import modules::CommonFuc
- import * from modules::CommonFunc
- import concatName stringToDateUTC from modules::CommonFunc
- CommonFunc::concatName(payload)
- concatName(payload)
For those who know python, you may find the syntax is very similar between the two languages, in terms of modules, and references.
Here is testing data:
{
"firstName" : "Gary",
"lastName" : "Liu",
"createdDate":"2018-07-17T16:18:03+00:00"
}
Published at DZone with permission of Gary Liu, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments