Search code examples
muleesbdataweave

Mule ESB Multiple when conditions in Dataweave


I am using dataweave, due to sales taxes in each state, I need to assign a each customer from a specific state to a pre-defined user. However when I create this in dataweave I end up with this as my XML:

<Customer>
<Number>
  <Number>
    <Number>
      <Number>WEB002</Number>
    </Number>
  </Number>
</Number>

I just need one 'number' node underneath the 'customer' node. Here is my dataweave:

Customer:{
Number: 'WEB001' when payload.order.billing_address.state == 'Indiana' otherwise
Number: 'WEB002' when payload.order.billing_address.state == 'Kentucky' otherwise
Number: 'WEB003' when payload.order.billing_address.state == 'Illinois' otherwise
Number: 'WEB004'
},

Have tried placing my conditions inside of brackets, no joy, have tried to wrap each condition in brackets, no joy. Is there a better way to do this?


Solution

  • you can put the mapping between state and number in a map/dictionary which would improve the readability like this:

    %var numbers = {
        Indiana: 'WEB001',
        Kentucky: 'WEB002',
        Illinois: 'WEB003'
    }
    

    this is what your dataweave would look like:

    %dw 1.0
    %output application/xml
    
    %var defaultNumber = 'WEB004'
    %var numbers = {
        Indiana: 'WEB001',
        Kentucky: 'WEB002',
        Illinois: 'WEB003'
    }
    
    ---
    Customer: {
        Number: numbers[payload.order.billing_address.state] 
            default defaultNumber
    }
    

    and here is a screenshot containing sample data and the resulting preview: enter image description here