AKB
AKB

Reputation: 5938

null check in DataWeave 2

I have a prams in my url and using in DW as:

<set-variable value=" #[output application/java --- ( (attributes.queryParams.filePath startsWith  ('/opt/mypath/')))] .../>

If I don't pass any params, I am getting exception as:

  Message               : "You called the function 'startsWith' with these arguments: 
       1: Null (null)
       2: String ("/opt/mypath/")

     But it expects arguments of these types:
       1: String
       2: String 
 1| output application/java --- ( (attributes.queryParams.filePath startsWith  ('/opt/mypath/')))

1) How do validate for null?

2) If there are no params are passed, then I want to return to user to give the params and avoid further flows. Is it possible to return in DataWeave? or do I need to use standard Groovy script to return?

Upvotes: 2

Views: 7338

Answers (1)

jerney
jerney

Reputation: 2243

You can use conditional logic to protect against null inputs like this:

if (attributes.queryParams.filePath != null) (attributes.queryParams.filePath startsWith '/opt/mypath/') else null

If you need to protect against an empty string as well, I'd use isEmpty:

if (isEmpty(attributes.queryParams.filePath)) null else (attributes.queryParams.filePath startsWith '/opt/mypath/')

However, if you validate that attributes.queryParams.filePath is not null beforehand, the DataWeave code can be more simple. Here's the whole thing. This will halt the whole flow and return an error if the query param is null:

<flow name="flow" doc:id="d891a730-794d-4ca5-b6d9-dd00238d89ba" >
  <http:listener doc:name="Listener" doc:id="a1cadeb8-d589-436c-8342-c13e065e4618" config-ref="HTTP_Listener_config" path="/test"/>
  <validation:is-not-null doc:name="Is not null" doc:id="66577b65-ba8d-4954-b3e7-e598310773ea" value="#[attributes.queryParams.filePath]" message='"filePath" must be included in the query parameters'/>
  <set-variable value="#[attributes.queryParams.filePath]" doc:name="Set Variable" doc:id="68511ea5-25cf-465f-ad89-c33a83ab83ec" variableName="filePath"/>
  <error-handler>
    <on-error-propagate enableNotifications="true" logException="true" doc:name="On Error Propagate" doc:id="ac12ae39-c388-4204-b1b1-b8c42aefcd66" >
    <ee:transform doc:name="Transform Message" doc:id="da695971-3ca4-435e-a4cd-b19fdd431bd6" >
      <ee:message >
        <ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
error.description
]]></ee:set-payload>
        </ee:message>
      </ee:transform>
    </on-error-propagate>
  </error-handler>
</flow>

Upvotes: 4

Related Questions