Различия

Показаны различия между двумя версиями страницы.

Ссылка на это сравнение

Предыдущая версия справа и слева Предыдущая версия
Следующая версия
Предыдущая версия
develop:mule:dataweave [2024/02/25 12:47] – [read] mirocowdevelop:mule:dataweave [2024/03/06 22:19] (текущий) – [Ссылки] mirocow
Строка 17: Строка 17:
 payload payload
 </code> </code>
 +
 +<note tip>IDE https://dataweave.mulesoft.com/learn/playground</note>
 +===== Oprators =====
 +
 +  * using: For initializing local variables in a DataWeave script.
 +  * Unary DataWeave operators at this level:
 +    * .^: Schema selector.
 +    * .#: Namespace selector.
 +    * ..: Descendants selector. 
 +    * not: Logical operator for negation.
 +    * .@: All attribute selector, for example, in a case that uses the expression payload.root.a.@ to return the attributes and values of the input payload <root> <a attr1="foo" attr2="bar" /></root> within the array of objects { "attr1": "foo", "attr2": "bar" }.                                                                                                                                                                                                                                              
 +==== Condition ====
 +
 +<code>
 +%dw 2.0
 +output application/json
 +---
 +{
 +    "result": if (vars.myVar == null) "myVar is null" else "myVar has a value set"
 +}
 +</code>
 +
 +<code>
 +%dw 2.0
 +var myVar = { country : "India" }
 +output application/json
 +---
 +if (myVar.country == "UAE")
 +  { currency: "EUR" }
 +else { currency: "RUPEES" }
 +</code>
 +
 +<code>
 +%dw 2.0
 +output application/json
 +var user = {"firstName": "Manik", "lastName": "Magar", "Address Line1" : "Address line 1"}
 +---
 +name : user mapObject {
 + ('$$' : '$') when ($ contains 'Ma')
 +}
 +</code>
 +
 +<code>
 +%dw 2.0
 +var aRecord =
 + [
 +    "bookId":"101",
 +    "title":"world history",
 +    "price":"19.99"
 + ]
 +output application/xml
 +---
 +{ examples:
 +    {
 +       ex1 : if (1 + 1 == 55) true
 +             else false,
 +       ex2 : if ([1,2,3,4][1] == 1) 1
 +             else "value of index 1 is not 1",
 +       ex3 : if (isEmpty(aRecord.bookId)) "ID is empty"
 +         else "ID is not empty",
 +       ex4 : aRecord.bookId map (idValue) -&gt;
 +         if (idValue as Number == 101) idValue as Number
 +         else "not 101"
 +    }
 +}
 +</code>
 +
 +<code>
 +%dw 2.0
 +output application/json
 +var user = {"firstName": "Manik", "lastName": "Magar", "Address Line1" : "Address line 1"}
 +---
 +name : user filter ($ contains "Ma")
 +</code>
 +
 +==== Filters ====
 +
 +
 +
 +
 +
 +
 +==== Functions ====
 +
 +  * Named functions
 +  * Lambdas
 +  * Passing functions to other functions
 +  * Calling 2-arity functions with infix notation
 +  * $, $$, $$$ syntax
 +
 +=== Лямда функции / Functions as Values ===
 +
 +Полезность лямбд становится очевидной, когда мы объединяем две идеи:
 +
 +  * Лямбды — это значения, такие же, как строки, объекты и логические значения.
 +  * Значения могут передаваться функциям в качестве аргументов, а также возвращаться из функций.
 +
 +В DataWeave функции и лямбды (анонимные функции) могут передаваться как значения или присваиваться переменным. 
 +
 +DataWeave предоставляет несколько способов создания функций. Точно так же, как у нас есть именованные функции, у нас есть функции без имен, называемые лямбда-выражениями. Лямбда — это значение в DataWeave, такое же, как строка, объект и логическое значение. При использовании лямбда-выражений в теле файла DataWeave в сочетании с такой функцией, как карта, его атрибутам можно либо дать явное имя, либо оставить анонимным, и в этом случае на них можно ссылаться как $, $$ и т. д.
 +
 +<note tip>Другими словами, лямбды становятся полезными, когда вы хотите передать функции в качестве аргументов другим функциям или вернуть функцию из функции.</note>
 +
 +<code>
 +%dw 2.0
 +output json
 +
 +fun isOddNum(n) =
 +  (n mod 2) == 1
 +
 +// Generate [1, 2, ..., 5]
 +var numbers = (1 to 5)
 +---
 +filter(numbers, (n, idx) -> isOddNum(n))
 +</code>
 +
 +<code>
 +%dw 2.0
 +output json
 +
 +var numbers = (1 to 5)
 +---
 +filter(numbers, (n, idx) -> (n mod 2) == 1)
 +</code>
 +
 +<code>
 +%dw 2.0
 +output json
 +---
 +(() -> 2 + 3)()
 +</code>
 +
 +<code>
 +%dw 2.0
 +output application/json
 +var toUser = (user) -> {
 +  firstName: user.field1,
 +  lastName: user.field2
 +}
 +---
 +{
 +  "user" : toUser(payload)
 +}
 +</code>
 +
 +=== Логические операторы / Logical Operators ===
 +
 +  * A > B Greater than
 +  * A < B Less than
 +  * A >= B Greater than or equal to
 +  * A <= B Less than or equal to
 +  * A == B Equal to
 +  * A != B Not equal to
 +  * A ~= B Similar to
 +  * not A Logical negation
 +  * !A Logical negation
 +  * A and B Logical and
 +  * A or B Logical or
 +  * not Negates the result of the input. See also, !.
 +  * ! Negates the result of the input. See also, not. Introduced in DataWeave 2.2.0. Supported by Mule 4.2 and later.
 +  * and Returns true if the result of all inputs is true, false if not.
 +  * or Returns true if the result of any input is true, false if not.
 +
 +<code>
 +%dw 2.0
 +output json
 +var age = 2
 +---
 +age < 10
 +</code>
 +
 +<code>
 +%dw 2.0
 +var myArray = [1,2,3,4,5]
 +var myMap = myArray map not (($ mod 2) == 0)
 +output application/json
 +---
 +{
 +  "not" : [
 +    "notTrue" : not true,
 +    "notFalse" : not false,
 +    "myMapWithNot" : myMap
 +  ],
 +  "and" : [
 +    "andTrueFalse" : true and false,
 +    "andIsTrue" : (1 + 1 == 2) and (2 + 2 == 4),
 +    "andIsFalse" : (1 + 1 == 2) and (2 + 2 == 2)
 +  ],
 +  "or" : [
 +    "orTrueFalse" : true or false,
 +    "orIsTrue" : (1 + 1 == 2) or (2 + 2 == 2),
 +    "orIsFalse" : (1 + 1 == 1) or (2 + 2 == 2)
 +  ],
 +  "!-vs-not" : [
 +      "example-!" : (! true or true),
 +      "example-not" : (not true or true)
 +  ]
 +}
 +</code>
 +
 +<code>
 +%dw 2.0
 +var orNot = if (1 + 1 == 4 or not 1 == 2) {"answer": "orNot - Condition met"}
 +             else {"answer": "nope"}
 +var andNot = if (1 + 1 == 2 and not 1 == 2) {"answer": "andNot - Condition met"}
 +             else {"answer": "nope"}
 +var notWithAndNot = if (not (1 + 1 == 2 and not 1 == 1)) {"answer": "notWithAndNot - Condition met"}
 +              else {"answer": "nope"}
 +output application/json
 +---
 +{ "answers" :
 +  [
 +    orNot,
 +    andNot,
 +    notWithAndNot
 +  ]
 +}
 +</code>
 +
 +=== Types ===
 +
 +<code>
 +%dw 2.0
 +output application/json
 +---
 +{
 +  /*
 +   * A multi-line
 +   * comment here.
 +   */
 +  myString: "hello world",
 +  myNumber: 123,
 +  myFloatingPointNumber: 123.456,
 +  myVeryBigNumber: 12341234134123412341234123,
 +  myDate: |2018-12-07|,
 +  myTime: |11:55:56|,
 +  myDateTime: |2018-10-01T23:57:59-03:00|,
 +  myBoolean: true,
 +  myArray: [ 1, 2, 3, 5, 8],
 +  myMixedArray: [ 1, 2, "blah", { hello: "there" } ],
 +  myObjectKeyValuePair: { innerKey: "innerValue" },
 +  myObjectWithConditionalField: { a : { b : 1, ( c : 2 ) if true, (d : 4) if false } },
 +  myNull: null,
 +  myBinary: "abcd1234123" as Binary
 +  //A one-line comment here.
 +}
 +</code>
 +===== dw::* =====
  
 ==== dw::core::Arrays / Working with Array ==== ==== dw::core::Arrays / Working with Array ====
Строка 40: Строка 288:
   * **takeWhile** Selects elements from the array while the condition is met but stops the selection process when it reaches an element that fails to satisfy the condition.   * **takeWhile** Selects elements from the array while the condition is met but stops the selection process when it reaches an element that fails to satisfy the condition.
  
 +=== divideBy ===
 +
 +<code>
 +%dw 2.0
 +import divideBy from dw::core::Objects
 +output application/json
 +---
 +{ "a": 1, "b": true, "a": 2, "b": false, "c": 3 } divideBy 2 
 +</code>
 +=== drop ===
 +
 +<code>
 +%dw 2.0
 +import * from dw::core::Arrays
 +var samplearray = ["124", "35454", "Sachin","Amit"]
 +output application/json
 +---
 + 
 +drop(samplearray, 2)
 +</code>
 +
 +=== indexOf ===
 +
 +<code>
 +%dw 2.0
 +import * from dw::core::Arrays
 +var samplearray = ["124", "35454", "Sachin","Amit"]
 +output application/json
 +---
 + 
 +indexOf(samplearray, "Sachin")
 +</code>
 +
 +=== join ===
 +
 +<code>
 +%dw 2.0
 +import * from dw::core::Arrays
 + 
 +var items = [{id: "12", name:"Tea"},{id: "22", name:"Salt"},{id: "3", name:"Soap"},{id: "5", name:"Butter"}]
 + 
 +var Prices = [{Id: "12", price:123},{Id: "3", price:24}, {Id: "22", price:20}, {Id: "4", price:456}]
 + 
 +output application/json
 +---
 +join(items, Prices, (item) -> item.id, (price) -> price.Id)
 +
 +</code>
 +=== takeWhile ===
 +
 +
 +<code>
 +%dw 2.0
 +import * from dw::core::Arrays
 +output application/json
 +var arr = [1,2,3,4,1,2]
 +---
 + 
 +arr takeWhile $ &lt;= 2
 +
 +</code>
 +
 +<code>
 +%dw 2.0
 +import * from dw::core::Objects
 +output application/json
 +var obj = {
 +  "a": 1,
 +  "b": 2,
 +  "c": 5,
 +  "d": 1
 +}
 +---
 +obj takeWhile ((value, key) ->  value < 3)
 +</code>
 ==== dw::Core ==== ==== dw::Core ====
  
Строка 53: Строка 376:
 --- ---
 payload distinctBy $.id payload distinctBy $.id
 +</code>
 +
 +<code>
 +%dw 2.0
 +output application/json
 +var str = [1,2,3,4,5,6,7]
 +var str1= [4,5,6,7,1]
 +---
 +(str ++ str1) distinctBy ((item, index) ->item )
 </code> </code>
  
Строка 320: Строка 652:
 </code> </code>
  
 +<code>
 +%dw 2.0
 +output application/json  
 +---
 +payload filterObject ((value, key) -> 
 +    (key as String != "first name"
 +    and (key as String != "last name")
 +)
 +</code>
 === flatten === === flatten ===
  
Строка 438: Строка 779:
 </code> </code>
  
 +<code>
 +%dw 2.0
 +output application/java
 +fun process(obj: Object) = obj mapObject ((value, key) -> {
 +    (key): key match {
 +        case "description" -> vars.descriptionValue
 +        else -> value
 +    }
 +})
 +---
 +payload map ((item, index) -> 
 +    process(item)
 +)
 +</code>
 === mapObject === === mapObject ===
  
Строка 591: Строка 946:
  
 So result will be 9 So result will be 9
 +</code>
 +
 +<code>
 +%dw 2.0
 +output application/json
 +
 +var data = {"xyz": {"abc":["account":[{"value":"savings"}]]}}
 +---
 +data..value reduce $
 </code> </code>
  
Строка 700: Строка 1064:
 </code> </code>
  
 +=== valuesOf ===
 +
 +<code>
 +%dw 2.0
 +output application/json
 +---
 +valuesOf(payload.responses) filter ($.fieldname ~= "verifyemail")
 +</code>
 <code> <code>
 %dw 2.0 %dw 2.0
Строка 740: Строка 1112:
   * **valueSet** Returns an array of the values from key-value pairs in an object.   * **valueSet** Returns an array of the values from key-value pairs in an object.
  
 +=== everyEntry ===
 +
 +<code>
 +%dw 2.0
 +import everyEntry from dw::core::Objects
 +output application/json
 +---
 +{
 +    a: {} everyEntry (value, key) -> value is String,
 +    b: {a: "", b: "123"} everyEntry (value, key) -> value is String,
 +    c: {a: "", b: 123} everyEntry (value, key) -> value is String,
 +    d: {a: "", b: 123} everyEntry (value, key) -> key as String == "a",
 +    e: {a: ""} everyEntry (value, key) -> key as String == "a",
 +    f: null everyEntry ((value, key) -> key as String == "a")
 +}
 +</code>
 +
 +=== mergeWith ===
 +
 +<code>
 +%dw 2.0
 +import mergeWith from dw::core::Objects
 +output application/json
 +---
 +{ "a" : true, "b" : 1} mergeWith { "a" : false, "c" : "Test"
 +</code>
 +
 +=== someEntry ===
 +
 +<code>
 +%dw 2.0
 +import someEntry from dw::core::Objects
 +output application/json
 +---
 +{
 +    a: {} someEntry (value, key) -> value is String,
 +    b: {a: "", b: "123"} someEntry (value, key) -> value is String,
 +    c: {a: "", b: 123} someEntry (value, key) -> value is String,
 +    d: {a: "", b: 123} someEntry (value, key) -> key as String == "a",
 +    e: {a: ""} someEntry (value, key) -> key as String == "b",
 +    f: null someEntry (value, key) -> key as String == "a"
 +}
 +</code>
 ==== dw::util::Values ==== ==== dw::util::Values ====
  
Строка 876: Строка 1291:
  
   * https://docs.mulesoft.com/dataweave/latest/   * https://docs.mulesoft.com/dataweave/latest/
 +  * https://mulesy.com/1-mulesoft-as-middleware-solution/
 +  * https://reddeveloper.ru/tags/mule
 +  * https://questu.ru/tag/mule/