Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically
Read here to learn a DataWeave(DWL 1.0) function to help you perform a requirement where you want to resolve a wildcard using a set of parameters.
Join the DZone community and get the full member experience.
Join For FreeMulesoft DataWeave is a simple powerful tool to transform data inside a flow. Numerous core operators and functions are already present to perform various operations such as capitalize, camelize, upper, and lower.
For string operations, there are no core functions present to resolve a wildcard. I hope the DataWeave(DWL 1.0) function below helps you to perform a requirement where you want to resolve a wildcard using a set of parameters.
Steps
Goal To Achieve Below:
Input: "This is to test wildcards.1st wildcard {1}, 2nd wildcard {2}, Nth wildcard {n}"
Output: "This is to test wildcards.1st wildcard 1, 2nd wildcard 2, Nth wildcard Wn"
Assuming passing set of wildcards as [1,2,"Wn"]
DataWeave Code:
%dw 1.0
%output application/json
%var inputString = "This is to test wildcards.1st wildcard {1}, 2nd wildcard {2}, Nth wildcard {n}"
%function reolveParam(unresolvedString,parameters=[])
using(propArr=unresolvedString splitBy /\{\w*\}/)
((flatten (propArr zip parameters) reduce ($$ ++ $)) when ((sizeOf propArr) > 1 ) otherwise unresolvedString)
---
reolveParam(inputString,[1,2,"Wn"])
Explanation:
Here in the above resolveParam
function, two inputs are needed. The first one is unresolvedString
which is mandatory with a wildcard. In this case "{}" is used as a wildcard pattern, and those are resolved with provided set of parameters
(2nd input) as an Array. unresolvedString
is split into an array(propArr)
of string tokens using the regex for the wildcard. Then, propArr
is zipped with parameters array using zip operator. Ultimately flatten
and reduce
operators help to achieve the resolved string.
The second parameter named parameters
is optional. In the case of an input string without a wildcard, there is no need to pass the 2nd parameter. The function could be invoked in this way resolveParam("This is an input without wildcard")
.
Your requirement might be a bit different, however, and changing a bit in the above code might help you achieve your program's goal. As a learning exercise, you could extend this function with another param with regex. I am leaving it up to you for your learning purposes.
A similar function in Mule 4(DWL 2.0) will also be added soon.
Opinions expressed by DZone contributors are their own.
Comments