Unraveling Data Challenges with DataWeave Part 6: Working with Custom Functions

Antonios Malliotis
Another Integration Blog
2 min readJul 24, 2023

Introduction

Hello again, aspiring DataWeave developers! Today, in part 6 of our series, we are going to discuss how to work with custom functions in DataWeave. Custom functions are extremely useful for encapsulating complex logic or calculations, improving code readability and reusability. Let’s dive right into our scenario for today!

Scenario

Let’s assume we’re working with an e-commerce company that keeps a record of all products they sell. For each product, they document its name, price, and the number of units sold. Their requirement is to calculate the total revenue each product has generated.

Here’s an example of the incoming payload:

{
"products": [
{
"name": "T-shirt",
"price": 29.99,
"unitsSold": 100
},
{
"name": "Jeans",
"price": 79.99,
"unitsSold": 50
},
{
"name": "Sneakers",
"price": 99.99,
"unitsSold": 20
}
]
}

Our goal is to transform this payload into a new structure, including the total revenue (in Euros) generated by each product

DataWeave Solution

To tackle this, we’ll create a custom function calculateRevenue in DataWeave. This function will take the product's price and the number of units sold as inputs and return the total revenue.

Here’s how we do it:

%dw 2.0
output application/json
fun calculateRevenue(price, unitsSold) = price * unitsSold
---
products: payload.products map (product) -> {
name: product.name,
revenue: calculateRevenue(product.price, product.unitsSold) ++ " €"
}

In the script, we define calculateRevenue using the fun keyword, followed by the function name and its parameters. We then use the = operator to define the body of the function. This function is invoked within the map function to calculate the revenue for each product. We also add the Euro (€) sign to the revenue by using the concatenation operator (++).

This results in the following output:

{
"products": [
{
"name": "T-shirt",
"revenue": "2999 €"
},
{
"name": "Jeans",
"revenue": "3999.5 €"
},
{
"name": "Sneakers",
"revenue": "1999.8 €"
}
]
}

Conclusion

In this part of the series, we’ve explored how to define and use custom functions in DataWeave. Custom functions help encapsulate logic, enhancing readability and reusability in our scripts. In the next part of this series, we will continue to explore more complex scenarios and dive deeper into DataWeave’s capabilities. Stay tuned!

--

--