Различия

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

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

Предыдущая версия справа и слева Предыдущая версия
Следующая версия
Предыдущая версия
develop:mule:dataweave [2024/02/25 12:43] 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>
  
Строка 318: Строка 650:
 --- ---
 payload [?( $.ticker contains "GO" )] payload [?( $.ticker contains "GO" )]
 +</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 несколько массивов объединяются в один массив.
 +
 +  * **items** The input array of arrays made up of any supported types.
 +
 +<code>
 +%dw 2.0
 +output application/json
 +---
 +flatten(payload)
 +</code>
 +
 +<code>
 +%dw 2.0
 +output application/json
 +var array1 = [1,2,3]
 +var array2 = [4,5,6]
 +var array3 = [7,8,9]
 +var arrayOfArrays = [array1, array2, array3]
 +---
 +flatten(arrayOfArrays)
 </code> </code>
 === groupBy === === groupBy ===
Строка 414: Строка 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 ===
  
Строка 569: Строка 948:
 </code> </code>
  
 +<code>
 +%dw 2.0
 +output application/json
  
 +var data = {"xyz": {"abc":["account":[{"value":"savings"}]]}}
 +---
 +data..value reduce $
 +</code>
 +
 +=== read ===
 +
 +  * **stringToParse** The string or binary to read.
 +  * **contentType** A supported format (or content type). Default: application/dw.
 +  * **readerProperties** Optional: Sets reader configuration properties. For other formats and reader configuration properties, see Supported Data Formats.
 +
 +<code>
 +%dw 2.0
 +output application/json
 +var inputData=
 +"name,age,salary
 +Joseph,34,3000
 +James,32,5000"
 +---
 +read(inputData,"application/csv")
 +</code>
 +
 +<code>
 +%dw 2.0
 +var myVar = "Some, Body"
 +output application/json
 +---
 +read(myVar,"application/csv",{header:false})[0]
 +</code>
 +
 +<code>
 +%dw 2.0
 +output application/xml
 +---
 +read('{ "hello" : "world" }','application/json')
 +</code>
 +
 +=== readUrl ===
 +
 +  * **url** The URL string to read. It also accepts a classpath-based URL. for example: classpath:\/\/myfolder/myFile.txt where myFolder is located under src/main/resources in a Mule project. Other than the URL, readURL accepts the same arguments as read.
 +  * **contentType** A supported format (or MIME type). Default: application/dw.
 +  * **readerProperties** Optional: Sets reader configuration properties. For other formats and reader configuration properties, see Supported Data Formats.
 +
 +<code>
 +%dw 2.0
 +output application/json
 +---
 +readUrl("classpath://employee.json","application/json")
 +</code>
 +
 +<code>
 +%dw 2.0
 +var myJsonSnippet = readUrl("classpath://myJsonSnippet.json", "application/json")
 +output application/csv
 +---
 +(myJsonSnippet.results map(item) -> item.profile)
 +</code>
 +
 +<code>
 +%dw 2.0
 +output application/json
 +---
 +readUrl("https://jsonplaceholder.typicode.com/users/5","application/json")
 +</code>
 +
 +<code>
 +%dw 2.0
 +output application/json
 +var inputData=readUrl("https://jsonplaceholder.typicode.com/users/5","application/json")
 +---
 +{
 +    name: inputData.name,
 +    username: inputData.username,
 +    email: inputData.email
 +}
 +</code>
 +=== splitBy ===
 +
 +Разбивает строку на массив строк на основе входного значения или соответствует части этой входной строки. Он отфильтровывает соответствующую часть из возвращаемого массива. Строка или регулярное выражение Java, используемое для разделения строки. Если какая-то часть строки не соответствует, функция вернет исходную неразбитую строку в массиве.
 +
 +Эта версия splitBy принимает регулярное выражение Java (регулярное выражение), соответствующее входной строке. Регулярное выражение может соответствовать любому символу во входной строке. Обратите внимание, что splitBy выполняет противоположную операцию joinBy.
 +
 +  * **text** The input string to split.
 +  * **regex** A Java regular expression used to split the string. If it does not match some part of the string, the function will return the original, unsplit string in the array.
 +
 +<code>
 +%dw 2.0
 +output application/json
 +---
 +{ "splitters" : {
 +   "split1" : "a-b-c" splitBy(/^*.b./),
 +   "split2" : "hello world" splitBy(/\s/),
 +   "split3" : "no match" splitBy(/^s/),
 +   "split4" : "no match" splitBy(/^n../),
 +   "split5" : "a1b2c3d4A1B2C3D" splitBy(/^*[0-9A-Z]/)
 +  }
 +}
 +</code>
 +
 +<code>
 +%dw 2.0
 +output application/json
 +---
 +{ "splitters" : {
 +    "split1" : "a-b-c" splitBy("-"),
 +    "split2" : "hello world" splitBy(""),
 +    "split3" : "first,middle,last" splitBy(","),
 +    "split4" : "no split" splitBy("NO")
 +   }
 +}
 +</code>
 +
 +=== valuesOf ===
 +
 +<code>
 +%dw 2.0
 +output application/json
 +---
 +valuesOf(payload.responses) filter ($.fieldname ~= "verifyemail")
 +</code>
 +<code>
 +%dw 2.0
 +output application/java
 +---
 +payload splitBy(" ")
 +</code>
 +
 +<code>
 +%dw 2.0
 +output application/java
 +---
 +payload splitBy(/s/)
 +</code>
 +
 +<code>
 +%dw 2.0
 +output application/json
 +---
 +"192.88.99.0/24" splitBy(/[.\/]/)
 +</code>
 +
 +<code>
 +%dw 2.0
 +output application/json
 +---
 +"192.88.99.0" splitBy(".")
 +</code>
  
 ==== Working with Objects / dw::core::Objects ==== ==== Working with Objects / dw::core::Objects ====
Строка 583: Строка 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 ====
  
Строка 719: Строка 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/