Le language DataWeave
CSV
%dw 2.0
output csv header=true
---
payload
%dw 2.0
output json
---
typeOf(1.545)
Selector
{
"name": "Ana",
"age": 29,
"dynamicKey": "age"
}
%dw 2.0
output json
---
{
fixed: payload.age,
dynamic: payload[payload.dynamicKey]
}
Multiple sélector
https://dataweave.mulesoft.com/learn/tutorial/3.4-Multi_Value_Selector
payload.movies.*title
Descendants selector
https://dataweave.mulesoft.com/learn/tutorial/3.5-Descendants_Selector
payload.customer..name
Operator
https://dataweave.mulesoft.com/learn/tutorial/4.2-Logical_Operators
Flow control
If else
il else retourne une valeur
%dw 2.0
output json
var action = if (payload.price < 100) "buy" else "hold"
---
{
price : payload.price,
action : action
}
Pattern Matching
{
"action": "buy"
}
%dw 2.0
output json
---
payload.action match {
case "buy" -> “Buy at market price"
case "sell" -> "Sell at market price"
case "hold" -> “Hold asset"
else -> "Invalid input"
}
Functions
%dw 2.0
output json
fun add(n, m) =
n + m
---
add(1,2)
lambda
%dw 2.0
output json
---
(() -> 2 + 3)()
or
%dw 2.0
output json
var add = (n, m) -> n + m
---
add(2, 3)
Création de variable uniquement pour la fonction
%dw 2.0
output json
fun diff(n) = do {
var start = n[0]
var end = n[-1]
---
end - start
}
---
diff([1990, 1995, 2002, 2008, 2021])
infix notation
https://dataweave.mulesoft.com/learn/tutorial/6.4-Infix_notation
%dw 2.0
output json
var numbers = (1 to 5)
---
numbers
filter ((n, idx) -> (n mod 2) == 1)
filter ((n, idx) -> (n > 3))
$,$$,$$$
https://dataweave.mulesoft.com/learn/tutorial/6.5-$,_$$,_$$$_syntax
Array
reduce
https://dataweave.mulesoft.com/learn/tutorial/7.5-reduce
Solution
%dw 2.0
output json
---
payload reduce ((n, total = {}) -> total ++ {(n.name):n.id} )
Challenge
https://dataweave.mulesoft.com/learn/tutorial/7.6-Challenge
%dw 2.0
output json
var weekdays = [
"mon",
"tue",
"wed",
"thu",
"fri",
"sat",
"sun"
]
// dayOfWeek is a value from 1 to 7
fun toWeekDay(date : String) : String = weekdays[(date as LocalDateTime).dayOfWeek - 1]
---
payload map ((item, index) -> item ++ {"day":toWeekDay(item.datetime)})
filter ((n, index) -> n.organizer == "Ross")
Object
https://dataweave.mulesoft.com/learn/tutorial/8.1-filterObject
Map object et array
https://dataweave.mulesoft.com/learn/tutorial/8.2-mapObject
%dw 2.0
output json
---
payload map ((item, index) ->
item mapObject ((value, key, index) -> {(lower(key)):upper(value)})
)
pluck
https://dataweave.mulesoft.com/learn/tutorial/8.3-pluck
%dw 2.0
output json
---
payload groupBy ((order, index) -> order.customer )
pluck ((value, key, ind) -> (value))