Dynamically Importing Dataweave Mapping As Custom Modules In Mule 4

Author: Mrunali Rane

Why to use Custom Mapping Files?
  • It is very usual for a Mulesoft Developer to have a use case where he or she must execute various DWL Mappings depending on the conditions.
  • In most cases the choice router comes as a solution. 
  • But what if there are more conditions and mappings in the future? The developer must update the code in such cases.
  • We may fix this problem by using Dataweave mapping as Custom Modules.
Where to write DWL Mappings as Custom Modules?
  • Create a subdirectory and file for your mapping module in the Studio project. Create a subfolder in src/main/resources named modules.
  • Create a custom module file with a DWL mapping, such as Accounts.dwl or HR.dwl.
  • Saving the module within src/main/resources makes it accessible for use in any DataWeave script within the Mule app in that project.
  • Create your function in your mapping file, for example:
How to Import the Mappings as Custom Modules?
  • To use the mapping file we need to import the module in the Transform Message component using Dataweave code. To get to the mapping body, a developer needs to use the function name.
  • Following are the steps:
    • Specify the import directive in the header.It’s either modules::HR or modules::Accounts in our case.
    • Invoke the Mapping::main function. In our example it is HR::hrdep or Accounts::accdep. The function expects payload as an input to perform the mapping.
    • Please refer to the below code snippet.
  • The following output will be created because our variable value is “HR.”

We use cookies on this site to enhance your user experience. For a complete overview of how we use cookies, please see our privacy policy.