MuleSoft

Cheat Sheet functii DataWeave MuleSoft

Petru Constantin
--13 min lectura
#mulesoft#dataweave#transformation#functions#cheatsheet

DataWeave 2.0 ofera functii built-in puternice pentru transformarea datelor. Acest cheat sheet acopera functiile esentiale cu exemple practice pentru dezvoltarea de zi cu zi in MuleSoft.

Functii pentru string-uri

Operatii de baza cu string-uri

%dw 2.0
output application/json
 
var sampleText = "  MuleSoft Integration Platform  "
 
---
{
  // Transformari de caz
  upper: upper("hello"),                    // "HELLO"
  lower: lower("HELLO"),                    // "hello"
  capitalize: capitalize("hello world"),    // "Hello World"
  camelize: camelize("hello-world"),        // "helloWorld"
  dasherize: dasherize("helloWorld"),       // "hello-world"
  underscore: underscore("helloWorld"),     // "hello_world"
 
  // Trimming
  trim: trim(sampleText),                   // "MuleSoft Integration Platform"
  trimLeft: trim(sampleText) >> left(8),    // "MuleSoft"
  trimRight: trim(sampleText) >> right(8),  // "Platform"
 
  // Operatii cu substing-uri
  substringBefore: substringBefore("hello@world.com", "@"),  // "hello"
  substringAfter: substringAfter("hello@world.com", "@"),    // "world.com"
  substringBeforeLast: substringBeforeLast("a.b.c", "."),    // "a.b"
  substringAfterLast: substringAfterLast("a.b.c", "."),      // "c"
 
  // Dimensiune si padding
  sizeOf: sizeOf("hello"),                  // 5
  leftPad: leftPad("42", 5, "0"),           // "00042"
  rightPad: rightPad("42", 5, "0"),         // "42000"
 
  // Operatii de cautare
  contains: contains("hello world", "world"),  // true
  startsWith: startsWith("hello", "he"),       // true
  endsWith: endsWith("hello", "lo"),           // true
  indexOf: "hello" find "l",                   // [2, 3]
 
  // Operatii de inlocuire
  replace: replace("hello", "l", "L"),         // "heLLo"
  replaceRegex: "abc123" replace /\d+/ with "XXX"  // "abcXXX"
}

Functii avansate pentru string-uri

%dw 2.0
output application/json
import * from dw::core::Strings
 
---
{
  // Split si join
  splitBy: "a,b,c" splitBy ",",             // ["a", "b", "c"]
  joinBy: ["a", "b", "c"] joinBy "-",       // "a-b-c"
 
  // Operatii cu caractere
  charCode: charCode("A"),                   // 65
  charCodeAt: charCodeAt("ABC", 1),          // 66
  fromCharCode: fromCharCode(65),            // "A"
 
  // Pluralizare
  pluralize: pluralize("box"),               // "boxes"
  singularize: singularize("boxes"),         // "box"
 
  // Ordinalizare
  ordinalize: ordinalize(1),                 // "1st"
  ordinalizeSecond: ordinalize(2),           // "2nd"
  ordinalizeThird: ordinalize(3),            // "3rd"
 
  // Operatii cu cuvinte
  words: words("hello world test"),          // ["hello", "world", "test"]
  lines: lines("line1\nline2\nline3"),       // ["line1", "line2", "line3"]
 
  // Functii de verificare
  isAlpha: isAlpha("hello"),                 // true
  isAlphanumeric: isAlphanumeric("hello123"), // true
  isNumeric: isNumeric("12345"),             // true
  isWhitespace: isWhitespace("   "),         // true
  isEmpty: isEmpty(""),                       // true
  isBlank: isBlank("   "),                   // true
 
  // Repetare si inversare
  repeat: repeat("ab", 3),                   // "ababab"
  reverse: reverse("hello")                  // "olleh"
}

Functii pentru array-uri

Operatii de baza cu array-uri

%dw 2.0
output application/json
 
var numbers = [1, 2, 3, 4, 5]
var users = [
  {name: "Alice", age: 30},
  {name: "Bob", age: 25},
  {name: "Charlie", age: 35}
]
 
---
{
  // Transformare
  map: numbers map ($ * 2),                  // [2, 4, 6, 8, 10]
  mapWithIndex: numbers map (item, idx) -> {
    index: idx,
    value: item
  },
 
  // Filtrare
  filter: numbers filter ($ > 2),            // [3, 4, 5]
  filterObject: users filter ($.age >= 30),  // Alice si Charlie
 
  // Reducere
  reduce: numbers reduce (a, b) -> a + b,    // 15
  reduceRight: [1, 2, 3] reduce (a, b) -> a - b,  // -4
 
  // Cautare
  find: users filter ($.name == "Bob"),      // [{name: "Bob", age: 25}]
  contains: numbers contains 3,              // true
 
  // Aplatizare
  flatten: [[1, 2], [3, 4], [5]] flatten,    // [1, 2, 3, 4, 5]
  flatMap: [[1, 2], [3, 4]] flatMap ($ map ($ * 2)),  // [2, 4, 6, 8]
 
  // Sortare
  orderBy: users orderBy $.age,              // Sortat dupa varsta crescator
  orderByDesc: users orderBy -$.age,         // Sortat dupa varsta descrescator
 
  // Grupare
  groupBy: users groupBy $.age > 28,         // Grupat dupa conditie
 
  // Distinct
  distinctBy: [1, 2, 2, 3, 3, 3] distinctBy $,  // [1, 2, 3]
 
  // Operatii de dimensiune
  sizeOf: sizeOf(numbers),                   // 5
  isEmpty: isEmpty([]),                       // true
 
  // Partitionare
  partition: numbers partition ($ > 3),      // {success: [4,5], failure: [1,2,3]}
}

Functii de manipulare array-uri

%dw 2.0
output application/json
import * from dw::core::Arrays
 
var items = [1, 2, 3, 4, 5]
 
---
{
  // Acces la elemente
  first: items[0],                           // 1
  last: items[-1],                           // 5
  head: items[0],                            // 1
  tail: items[1 to -1],                      // [2, 3, 4, 5]
 
  // Operatii de taiere
  slice: items[1 to 3],                      // [2, 3, 4]
  take: items take 3,                        // [1, 2, 3]
  drop: items drop 2,                        // [3, 4, 5]
  takeWhile: items takeWhile ($ < 4),        // [1, 2, 3]
  dropWhile: items dropWhile ($ < 4),        // [4, 5]
 
  // Combinare
  concat: items ++ [6, 7],                   // [1, 2, 3, 4, 5, 6, 7]
  prepend: 0 >> items,                       // [0, 1, 2, 3, 4, 5]
  append: items << 6,                        // [1, 2, 3, 4, 5, 6]
 
  // Operatii de set
  union: [1, 2, 3] ++ [3, 4, 5] distinctBy $,  // [1, 2, 3, 4, 5]
  intersection: ([1, 2, 3] filter ([3, 4, 5] contains $)),  // [3]
  difference: [1, 2, 3] filter (not ([3, 4, 5] contains $)),  // [1, 2]
 
  // Impartire in bucati
  divideBy: items divideBy 2,                // [[1, 2], [3, 4], [5]]
 
  // Operatii zip
  zip: [[1, 2], ["a", "b"]] reduce (a, b) ->
    (a zip b) map ($ joinBy ":"),            // ["1:a", "2:b"]
 
  // Suma si statistici
  sum: sum(items),                           // 15
  avg: avg(items),                           // 3
  min: min(items),                           // 1
  max: max(items),                           // 5
 
  // Operatii cu index
  indexOf: items indexOf 3,                  // 2
  lastIndexOf: [1, 2, 3, 2, 1] lastIndexOf 2,  // 3
 
  // Verificari booleene
  every: items every ($ > 0),                // true
  some: items some ($ > 4),                  // true
  none: items every ($ < 0)                  // false (folosind every cu negatie)
}

Functii pentru obiecte

Operatii de baza cu obiecte

%dw 2.0
output application/json
 
var user = {
  firstName: "John",
  lastName: "Doe",
  email: "john@example.com",
  age: 30
}
 
---
{
  // Operatii cheie-valoare
  keys: keysOf(user),                        // ["firstName", "lastName", "email", "age"]
  values: valuesOf(user),                    // ["John", "Doe", "john@example.com", 30]
  entries: entriesOf(user),                  // [{key: "firstName", value: "John"}, ...]
 
  // Transformare
  mapObject: user mapObject {
    (upper($$)): $
  },                                         // {FIRSTNAME: "John", ...}
 
  // Filtrare
  filterObject: user filterObject ($ is String),  // Elimina age
 
  // Pluck (extrage valori cu transformare)
  pluck: user pluck {
    field: $$,
    val: $
  },
 
  // Merge obiecte
  merged: user ++ {country: "USA", age: 31}, // Suprascrie age
 
  // Sterge chei
  withoutAge: user - "age",                  // Obiect fara age
  withoutMultiple: user -- ["age", "email"], // Sterge mai multe chei
 
  // Redenumeste chei
  renamed: user mapObject ((v, k) ->
    if (k ~= "firstName") {first_name: v}
    else if (k ~= "lastName") {last_name: v}
    else {(k): v}
  ),
 
  // Valori default
  withDefault: user.middleName default "N/A",  // "N/A"
 
  // Null safety
  safeAccess: user.address?.city default "Unknown",
 
  // Verifica existenta
  hasKey: user.firstName?,                   // true
  keyPresent: user["firstName"]?             // true
}

Constructie dinamica de obiecte

%dw 2.0
output application/json
 
var fieldMappings = [
  {source: "fn", target: "firstName"},
  {source: "ln", target: "lastName"},
  {source: "em", target: "email"}
]
 
var sourceData = {
  fn: "Jane",
  ln: "Smith",
  em: "jane@example.com"
}
 
---
{
  // Constructie chei dinamice
  dynamicKeys: {
    ("user_" ++ "name"): "John",
    ("user_" ++ "id"): 123
  },
 
  // Chei conditionale
  conditionalObject: {
    name: "Test",
    (if (true) {active: true} else {}),
    (if (false) {hidden: true} else {})
  },
 
  // Din entries
  fromMappings: fieldMappings reduce ((mapping, acc = {}) ->
    acc ++ {(mapping.target): sourceData[mapping.source]}
  ),
 
  // Transformare recursiva de obiecte
  deepTransform: do {
    fun transform(obj) = obj match {
      case o is Object -> o mapObject ((v, k) ->
        {(lower(k as String)): transform(v)}
      )
      case a is Array -> a map transform($)
      else -> obj
    }
    ---
    transform({FirstName: "John", Address: {City: "NYC", ZIP: "10001"}})
  }
}

Functii pentru date si timp

Operatii cu date

%dw 2.0
output application/json
import * from dw::core::Periods
 
var today = now()
 
---
{
  // Data/timp curent
  now: now(),
  todayDate: now() as Date,
  currentTime: now() as Time,
 
  // Parsare date
  parseDate: "2025-01-15" as Date,
  parseDateTime: "2025-01-15T10:30:00Z" as DateTime,
  parseCustom: "15/01/2025" as Date {format: "dd/MM/yyyy"},
 
  // Formatare
  formatDate: today as String {format: "yyyy-MM-dd"},
  formatDateTime: today as String {format: "yyyy-MM-dd'T'HH:mm:ss"},
  formatCustom: today as String {format: "MMMM dd, yyyy"},
  formatLocale: today as String {format: "EEEE, MMMM d, yyyy", locale: "en-US"},
 
  // Extrage componente
  year: today.year,
  month: today.month,
  day: today.day,
  hour: today.hour,
  minute: today.minutes,
  second: today.seconds,
  dayOfWeek: today.dayOfWeek,
  dayOfYear: today.dayOfYear,
 
  // Aritmetica cu date
  addDays: today + |P7D|,                    // Adauga 7 zile
  subtractDays: today - |P7D|,               // Scade 7 zile
  addMonths: today + |P1M|,                  // Adauga 1 luna
  addYears: today + |P1Y|,                   // Adauga 1 an
  addHours: today + |PT2H|,                  // Adauga 2 ore
  addMinutes: today + |PT30M|,               // Adauga 30 minute
 
  // Comparatie
  isBefore: |2025-01-01| < |2025-12-31|,     // true
  isAfter: |2025-12-31| > |2025-01-01|,      // true
  isEqual: |2025-01-01| == |2025-01-01|,     // true
 
  // Perioada intre date
  daysBetween: |2025-01-01| - |2025-01-15|,  // Period
 
  // Operatii cu timezone
  withTimezone: today >> "America/New_York" as TimeZone,
  utc: today >> |+00:00|,
 
  // Inceputul/sfarsitul perioadelor
  startOfDay: today as Date ++ |T00:00:00|,
  endOfDay: today as Date ++ |T23:59:59|
}

Functii pentru perioade si durate

%dw 2.0
output application/json
import * from dw::core::Periods
 
---
{
  // Definitii de perioade
  oneDay: |P1D|,
  oneWeek: |P7D|,
  oneMonth: |P1M|,
  oneYear: |P1Y|,
  complex: |P1Y2M3D|,
 
  // Durata (bazata pe timp)
  oneHour: |PT1H|,
  thirtyMinutes: |PT30M|,
  tenSeconds: |PT10S|,
  combined: |PT1H30M|,
 
  // Aritmetica cu perioade
  doublePeriod: |P7D| * 2,                   // 14 zile
  halfPeriod: |P10D| / 2,                    // 5 zile
 
  // Calcul varsta
  birthDate: |1990-05-15|,
  age: do {
    var birth = |1990-05-15|
    var today = now() as Date
    ---
    years(between(birth, today))
  },
 
  // Calcul zile lucratoare
  businessDays: do {
    fun addBusinessDays(startDate, days) = do {
      var result = startDate + |P1D|
      var dayOfWeek = result.dayOfWeek
      ---
      if (days <= 0) startDate
      else if (dayOfWeek == 6 or dayOfWeek == 7)
        addBusinessDays(result, days)
      else
        addBusinessDays(result, days - 1)
    }
    ---
    addBusinessDays(|2025-01-06|, 5)         // Sare peste weekend-uri
  }
}

Functii de conversie de tip

Conversii de tip

%dw 2.0
output application/json
 
---
{
  // Conversii la string
  numberToString: 123 as String,             // "123"
  boolToString: true as String,              // "true"
  dateToString: |2025-01-15| as String,      // "2025-01-15"
 
  // Conversii la number
  stringToNumber: "123" as Number,           // 123
  stringToFloat: "123.45" as Number,         // 123.45
  boolToNumber: true as Number,              // 1
 
  // Conversii la boolean
  stringToBool: "true" as Boolean,           // true
  numberToBool: 1 as Boolean,                // true
  zeroBool: 0 as Boolean,                    // false
 
  // Conversii la date
  stringToDate: "2025-01-15" as Date,
  stringToDateTime: "2025-01-15T10:30:00Z" as DateTime,
  epochToDateTime: 1704067200000 as DateTime {unit: "milliseconds"},
 
  // Conversii binare
  stringToBase64: "Hello" as Binary,
  base64ToString: "SGVsbG8=" as String {encoding: "UTF-8"},
 
  // Verificare tip
  isString: "hello" is String,               // true
  isNumber: 123 is Number,                   // true
  isArray: [1,2,3] is Array,                 // true
  isObject: {a: 1} is Object,                // true
  isNull: null is Null,                      // true
 
  // Conversie sigura cu default
  safeNumber: ("abc" as Number default 0),   // 0
  safeDate: ("invalid" as Date default |2025-01-01|),
 
  // Typeof
  typeOfString: typeOf("hello"),             // "String"
  typeOfNumber: typeOf(123),                 // "Number"
  typeOfArray: typeOf([1,2,3]),              // "Array"
  typeOfObject: typeOf({a: 1})               // "Object"
}

Functii utilitare

Utilitare comune

%dw 2.0
output application/json
import * from dw::core::Numbers
import * from dw::Runtime
 
---
{
  // Gestionare null
  nullDefault: null default "fallback",      // "fallback"
  isBlankCheck: isBlank(""),                 // true
 
  // Expresii conditionale
  ifElse: if (true) "yes" else "no",
  unless: unless (false) "executed",
 
  // Expresii match
  matchType: "hello" match {
    case s is String -> "E un string: " ++ s
    case n is Number -> "E un numar"
    else -> "Tip necunoscut"
  },
 
  // Pattern matching
  matchPattern: "user@example.com" match {
    case email if (email contains "@") -> "Format de email valid"
    else -> "Invalid"
  },
 
  // Generare UUID
  uuid: uuid(),
 
  // Numere aleatoare
  randomInt: randomInt(100),                 // 0-99
  random: random() * 100,                    // 0.0-99.9
 
  // Operatii numerice
  round: round(3.7),                         // 4
  floor: floor(3.7),                         // 3
  ceil: ceil(3.2),                           // 4
  abs: abs(-5),                              // 5
  sqrt: sqrt(16),                            // 4
  pow: pow(2, 3),                            // 8
  mod: mod(10, 3),                           // 1
 
  // Logging (output in consola)
  logged: log("Debug message", {key: "value"}),
 
  // Gestionare erori
  tryCatch: try(() -> "123" as Number) default -1,
 
  // Functii recursive
  factorial: do {
    fun fact(n) = if (n <= 1) 1 else n * fact(n - 1)
    ---
    fact(5)                                  // 120
  },
 
  // Pattern de memoizare
  fibonacci: do {
    var cache = {}
    fun fib(n) =
      if (n <= 1) n
      else fib(n - 1) + fib(n - 2)
    ---
    fib(10)                                  // 55
  }
}

Functii binare si de encoding

%dw 2.0
output application/json
import * from dw::core::Binaries
 
var originalText = "Hello MuleSoft!"
 
---
{
  // Encodare/decodare Base64
  toBase64: toBase64(originalText as Binary),
  fromBase64: fromBase64("SGVsbG8gTXVsZVNvZnQh") as String,
 
  // Encodare Hex
  toHex: toHex("ABC" as Binary),
 
  // Encodare URL
  urlEncode: encodeURI("hello world & special=chars"),
  urlDecode: decodeURI("hello%20world%20%26%20special%3Dchars"),
 
  // Functii hash
  md5: do {
    import dw::Crypto
    ---
    Crypto::hashWith("Hello" as Binary, "MD5")
  },
 
  sha256: do {
    import dw::Crypto
    ---
    Crypto::hashWith("Hello" as Binary, "SHA-256")
  },
 
  // HMAC
  hmacSha256: do {
    import dw::Crypto
    ---
    Crypto::HMACWith("message" as Binary, "secret" as Binary, "HmacSHA256")
  }
}

Functii specifice XML

Operatii XML

%dw 2.0
output application/xml
 
var xmlData = read('<root xmlns:ns="http://example.com">
  <ns:item id="1">Value 1</ns:item>
  <ns:item id="2">Value 2</ns:item>
</root>', "application/xml")
 
---
{
  // Gestionare namespace-uri
  withNamespace: {
    ns0#root @(xmlns#ns0: "http://example.com"): {
      ns0#element: "value"
    }
  },
 
  // Sectiuni CDATA
  withCDATA: {
    root: {
      script: "<![CDATA[function() { return true; }]]>" as CData
    }
  },
 
  // Atribute
  withAttributes: {
    element @(id: "123", class: "main"): "content"
  },
 
  // Processing instructions
  withPI: {
    "?xml-stylesheet": {
      "@type": "text/xsl",
      "@href": "style.xsl"
    }
  },
 
  // Comentarii
  withComment: {
    root: {
      "!--": "Acesta este un comentariu",
      element: "value"
    }
  }
}

Tabel de referinta rapida

| Categorie | Functie | Exemplu | Rezultat | |-----------|---------|---------|----------| | String | upper | upper("abc") | "ABC" | | String | lower | lower("ABC") | "abc" | | String | trim | trim(" abc ") | "abc" | | String | replace | "abc" replace "b" with "B" | "aBc" | | Array | map | [1,2] map $ * 2 | [2,4] | | Array | filter | [1,2,3] filter $ > 1 | [2,3] | | Array | reduce | [1,2,3] reduce $$ + $ | 6 | | Array | flatten | [[1],[2]] flatten | [1,2] | | Object | mapObject | {a:1} mapObject {(upper $$): $} | {A:1} | | Object | keysOf | keysOf({a:1}) | ["a"] | | Date | now | now() | DateTime curent | | Date | as Date | "2025-01-15" as Date | Obiect Date | | Type | as String | 123 as String | "123" | | Type | as Number | "123" as Number | 123 | | Utility | uuid | uuid() | String UUID | | Utility | default | null default "x" | "x" |

Concluzie

Acest cheat sheet acopera functiile esentiale DataWeave 2.0 pentru dezvoltarea MuleSoft. Salveaza aceasta referinta pentru consultare rapida in timpul dezvoltarii transformarilor. Exerseaza combinarea acestor functii pentru a construi transformari de date complexe in mod eficient.


Sistemul tau AI e conform cu EU AI Act? Evaluare gratuita de risc - afla in 2 minute →

Ai nevoie de ajutor cu conformitatea EU AI Act sau securitatea AI?

Programeaza o consultatie gratuita de 30 de minute. Fara obligatii.

Programeaza un Apel

Weekly AI Security & Automation Digest

Get the latest on AI Security, workflow automation, secure integrations, and custom platform development delivered weekly.

No spam. Unsubscribe anytime.