Devendra
Devendra

Reputation: 221

Define global dataweave function in mule 3

I am defining the global function for payload but in the dataweave 1.0 I am not able to do the task. I have to define a separate global dataweave file where I have to add the conditions for payload like if gender== "male" then title= "mr." How can I perform the task. I have added my input and expected payload.

input payload:

{
    "persons": [
        {
            "name": "Devendra",
            "gender": "male",
            "age": 25
        },
        {
            "name": "aman",
            "gender": "male",
            "age": 16
        }
    ]
}

expected payload:

{
    "persons": [
        {
            "title": "MR.",
            "name": "Devendra",
            "gender": "male",
            "age": 25,
            "adult": true
        },
        {
            "title": "MS.",
            "name": "Seema",
            "gender": "female",
            "age": 16,
            "adult": false
        }
    ]
}

Upvotes: 1

Views: 987

Answers (1)

Ryan Carter
Ryan Carter

Reputation: 11606

In Dataweave 1 you can define a global library by creating a dwl file in src/main/resources like so:

src/main/resources/dw/myFunctions.dwl:

%dw 1.0
%function titleForGender(gender)("mr" when gender=="male" otherwise "whoKnows?")
---
{
"titleForGender": titleForGender
}

This script creates a global function and then exposes it in the body so its available to the other script.

Then in your main dw transformation something like this:

%dw 1.0
%output application/json

%var sampleData={persons:[{name:"Devendra", gender:"male",age:25}, {name:"aman", gender:"male",age:16}]}
%var lib = readUrl("classpath://dw/myfunctions.dwl")
 ---
persons: sampleData.persons map {
    "person": $ ++ {title: lib.titleForGender($.gender)}
}

It uses readUrl to read in the function from the global file as var lib and then uses it when mapping the person data, passing in the gender to the function and getting the title returned from the function.

This outputs:

{
  "persons": [
    {
      "person": {
        "name": "Devendra",
        "gender": "male",
        "age": 25,
        "title": "mr"
      }
    },
    {
      "person": {
        "name": "aman",
        "gender": "male",
        "age": 16,
        "title": "mr"
      }
    }
  ]
}

Upvotes: 2

Related Questions