Search code examples
wso2esbwso2-enterprise-integratoreiwso2-esb

WSO2 EI/ESB: Implementing Switch mediator and Filter mediator using Regular Expression


In my API, I have a property like:

<property expression="json-eval($.Entity.users.name)" name="uri.var.name"/>

I want to use Switch mediator and Filter mediator to route to different back-ends based on the above property.

For example, if the property can have 4 different values : Nick, Tom, Jade, Dave

  1. If the property has name Nick or Jade, it will point to back-end-1.

  2. If the property has name Tom or Dave, it will point to back-end-2.

    <switch source="json-eval(uri.var.name)">
       <case regex="Nick|Jade">
          <send>
             <endpoint>
                <http method="get" uri-template="https://backend1.com" />
             </endpoint>
          </send>
       </case>
       <case regex="Tom|Dave">
          <send>
             <endpoint>
                <http method="get" uri-template="https://backend2.com" />
             </endpoint>
          </send>
       </case>
       <default />
    </switch>

This is not working. What is the proper way of defining the Source and Regex in Switch mediator?

Similarly in the Filter mediator also!


Solution

  • You are using the wrong expression for the Source here. You are correctly reading the name and saving it to a property using a JSONPath expression. Please note here that json-eval() indicates that you are using a JSONPath here. Default is XPATH (that's why!!!).

    After you create the property, the property will reside in the Message Context. To read a property in the Message Context, you need to use $ctx:uri.var.name. $ctx indicates that you are reading it from the Message Context. JSONPath is used read from the Message payload, not the Message Context.

    With the above information, change your switch mediator as below.

    <switch source="$ctx:uri.var.name">
       <case regex="Nick|Jade">
          <send>
             <endpoint>
                <http method="get" uri-template="https://backend1.com" />
             </endpoint>
          </send>
       </case>
       <case regex="Tom|Dave">
          <send>
             <endpoint>
                <http method="get" uri-template="https://backend2.com" />
             </endpoint>
          </send>
       </case>
       <default />
    </switch>
    

    For reference look at the following documentations. https://docs.wso2.com/display/EI660/Accessing+Properties+with+XPath#AccessingPropertieswithXPath-SynapseXPathVariables https://docs.wso2.com/display/EI660/Working+with+JSON+Message+Payloads+#WorkingwithJSONMessagePayloads-AccessingcontentfromJSONpayloads