DataWeave (DW) has been part of the MuleSoft family from v3.7.0.
Below listed ones are the few tips and best practices which could be useful in DW.
There are many operators in dataweave which can make our life easy espically for complex dataweave transformation.
There are many operators in dataweave which can make our life easy espically for complex dataweave transformation.
DataWeave-Playground is a online tool to experiment the DataWeave stuff without doing it from Anypoint Studio.
URL: I like it, please use the playground for better learning..
Sample Payload:
{
"name": "Sravan Kumar",
"age": 30,
"profession": "Mulesoft Developer",
"date": "2022-04-21T10:03:45-04:00",
"comment": "Special characters. "
}
"name": "Sravan Kumar",
"age": 30,
"profession": "Mulesoft Developer",
"date": "2022-04-21T10:03:45-04:00",
"comment": "Special characters. "
}
1. Dealing special characters ($)
If you have some special character (e.g. “, $ etc) in your payload. Here is how you can deal them in dataweave using “\”.
%dw 2.0
output application/json
---
{
name: payload.name,
age: payload.age,
profession: payload.profession,
date: payload.date,
comment: payload.comment ++ "\$\$ handling special character \$\$"
}
2. Pattern matching
If you want to evaluate that payload.name has any number in it.?
Use regex..it will return true or false only.
%dw 2.0
output application/json
---
{
name: payload.name,
age: payload.age,
profession: payload.profession,
date: payload.date,
comment: payload.comment ++ "\$\$ handling special character \$\$",
"regex_number_check" : payload.name contains /\d+/
}
3.Comments - Useful for easy reading the DW
// Single line comment like JAVA
/*
Multiline comments
*/
Multiline comments
*/
4. Null check - is very useful.
isEmpty(payload.name) - returns true if name is null, else false
5. Add/update a key/s of an object
If you want to add or update the value of key of an object. Here is written small snippt..
If the key is not present in the payload, then it would add a new key to the object otherwise it would update the existing key’s value
Remove key/s of an object
%dw 2.0
output application/json
---
payload -- ["date","comment"]
output application/json
---
payload -- ["date","comment"]
6. Use custom dataweave modules for re-usability across the organization.
Create a file under => src/main/resources/dw/common.dwl
%dw 2.0
fun getUpdatedsting(value:String) = "Welcome" ++" " ++ value
%dw 2.0
fun getUpdatedsting(value:String) = "Welcome" ++" " ++ value
DW-Transformation
%dw 2.0
output application/json
import dw::common
---
{
name: payload.name,
age: payload.age,
profession: payload.profession,
Welcome : common::getUpdatedsting("Jai"),
comment: payload.comment
}
%dw 2.0
output application/json
import dw::common
---
{
name: payload.name,
age: payload.age,
profession: payload.profession,
Welcome : common::getUpdatedsting("Jai"),
comment: payload.comment
}
Ref:
No comments:
Post a Comment