Saturday, August 4, 2018

Mule 4 : Dataweave 2 In Action - Use Function Modules

Introduction

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.

Define Functions In Dataweave Modules

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.

Use Function Modules

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 functions
    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.

Testing Data

Here is the complete flow:
 
  
   
  
  
   
    
   
  
  
 
Here is testing data:
{
 "firstName" : "Gary",
 "lastName" : "Liu",
 "createdDate":"2018-07-17T16:18:03+00:00"
}

6 comments:

  1. For Mulesoft ESB Real Time Training Contact Me at muleesbtrainer@gmail.com and 9985333565

    I will provide real time online training at low price for demo videos visit my youtube channel.
    http://youtube.com/channel/UC1lFGEh4xAPJnIm4FWmQBfA

    ReplyDelete
  2. Very informative post for mulesoft developers.You can also visit goformule.com for mulesoft stuff.

    ReplyDelete
  3. Thanks for Posting such an useful & informative stuff..

    mulesoft training

    ReplyDelete
  4. Thank you for sharing wonderful information with us to get some idea about it.
    Mulesoft Training in Bangalore
    Best Mulesoft Online Training

    ReplyDelete

Anypoint Studio Error: The project is missing Munit lIbrary to run tests

Anypoint Studio 7.9 has a bug. Even if we following the article: https://help.mulesoft.com/s/article/The-project-is-missing-MUnit-libraries-...