{{announcement.body}}
{{announcement.title}}

Mule 4: Dataweave 2 In Action: Use Function Modules

DZone 's Guide to

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.

· Integration Zone ·
Free Resource

In 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:

  1. import modules::CommonFuc
  2. import * from modules::CommonFunc
  3. import concatName stringToDateUTC from modules::CommonFunc
  • use functions in dwl
    1. CommonFunc::concatName(payload)
    2. 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"
    }
    Topics:
    integration ,tutorial ,mule 4 ,dataweave 2 ,function models

    Published at DZone with permission of

    Opinions expressed by DZone contributors are their own.

    {{ parent.title || parent.header.title}}

    {{ parent.tldr }}

    {{ parent.urlSource.name }}