A Non-conventional use of DataWeave

A Non-conventional use of DataWeave

DataWeave makes data transformation easier to code, more scalable, and efficient.

You can create DataWeave scripts as metadata and invoke them from Apex (and consequently, from flows).

The major benefit is that it frees us up from having to dive too deeply in details to handle different file formats.

The major file formats it can handle are:

  • CSV
  • Java object
  • JSON
  • XML

In this quick proof-of-concept, I am converting a JSON response from a currency rate web service into a HTML Table to be displayed on a rich text field.

But there is no "official" HTML format available in DataWeave!

Right, but you can use XML and specify "writeDeclaration=false" to get the same effect.

Here is how:

%dw 2.0
input payload application/json
output application/xml writeDeclaration=false
---
div @(style:"height: 300px; overflow-y: scroll;"):
table @(style:"width: 50%; border: 1px solid gray; font-family: Arial"): { 
    thead @(style:"border: 1px solid gray; font-weight: bold"): 
        tr: { td: "Currency", td: "Rate" },
    tbody: ( payload.conversion_rates mapObject (
            (v, k) -> tr: { td: k, td: v } 
        ) 
    )
}        

In the above DataWeave script, the currency conversion rates in a JSON payload variable are transformed into a table contained in a div with CSS styling.

The table has 2 columns Currency and Rate and the rows are populated from "payload.conversion_rates" (JSON).

In the DataWeave Playground at https://dataweave.mulesoft.com/learn/dataweave you can test and see the results before creating the DataWeave script in Salesforce.

I've used a flow to test this concept:

  • it calls an Apex class "GetExchangeRates" to call the web service at https://www.exchangerate-api.com/ and retrieves currency rates (JSON format)
  • it calls another Apex class "DataWeaveConversionHelper" to apply the DataWeave transformation to the JSON data
  • then it exposes the HTML table in a rich text field (LWC)


This is the result:

The flow configuration: notice that there is no loops to parse the response or to extract currency codes and rates or format them - everything is done by that little DataWeave script.

The source code is at https://github.com/Fernando-Fernandez/DataWeaveToHTML



要查看或添加评论,请登录

社区洞察

其他会员也浏览了