Skip to content

Instantly share code, notes, and snippets.

@aimtiaz11
Created October 19, 2022 06:14
Show Gist options
  • Save aimtiaz11/81ac0bc2037a56cc5dbc1c6ab2845aa9 to your computer and use it in GitHub Desktop.
Save aimtiaz11/81ac0bc2037a56cc5dbc1c6ab2845aa9 to your computer and use it in GitHub Desktop.
Multiple Payload Validation Error using Mule 4 Dataweave

Multiple payload validations in single Mule Dataweave file

Try it out here: https://developer.mulesoft.com/learn/dataweave/

Input

{
    "name": "apple",
    "birthYear": "1950"
}

Script

Target should be a vars. For example, vars.validationErrors

%dw 2.0
output application/json skipNullOn="everywhere"

// Put each validation + error message into a var to evaluate later in a function
var nameErr = if(!(payload.name startsWith "i")) "Name not starting with letter i" else null
var birthYearErr = if(payload.birthYear != "1990") "Birth year is not 1990" else null

// Reusable function to process each error messages evaluated in a var above
fun processError(code, errMsg) = (
    if(errMsg != null) 
        {
            code: code,
            message: errMsg

        } 
    else 
        null
)
---
{
    errors: [
        processError('INVALID_NAME', nameErr),
        processError('INVALID_DOB', birthYearErr)
    ]
        
  
}

Output

{
  "errors": [
    {
      "code": "INVALID_NAME",
      "message": "Name not starting with letter i"
    },
    {
      "code": "INVALID_DOB",
      "message": "Birth year is not 1990"
    }
  ]
}

Validation Component

<ee:transform doc:name="Set Var - Run Validation" doc:id="3dcb0f78-064c-4ce1-9759-d308a081dcae">
    <ee:variables>
        <ee:set-variable resource="mappings/run-validation.dwl" variableName="validationErrors" />
    </ee:variables>
</ee:transform>


<ee:transform doc:name="Set Var - Set Validation Error Count" doc:id="a83e9ead-cdd6-4bbd-ae3d-b32f45f0e994">
    <ee:variables>
        <ee:set-variable variableName="errorSize">
            <![CDATA[%dw 2.0
output application/java
---
sizeOf(vars.validationErrors.errors)]]>
        </ee:set-variable>
    </ee:variables>

    <validation:is-true doc:name="Any validation errors?" doc:id="404c6211-fb85-4ec4-8924-5da257306a11" expression="#[vars.errorSize == 0]">
        <error-mapping targetType="APP:PAYLOAD_VALIDATION" />
    </validation:is-true>

Error handler

<on-error-continue enableNotifications="true" logException="true" 
doc:name="On Error Continue" doc:id="3244b570-63c1-4419-8b1c-208095d1eaf2" 
type="APP:PAYLOAD_VALIDATION">

    <set-variable value="400" 
    doc:name="Set HTTP Status = 400" 
    doc:id="94a4451d-b339-48c7-a30e-4cd0eec9f59f" 
    variableName="httpStatus" />

    <set-payload value="#[vars.validationErrors]" doc:name="Set Payload" doc:id="147339b4-504e-42aa-b9f6-c79bb51af4ef" />
</on-error-continue>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment