DataWeave Tip #8: The write Function

Originally published February 26, 2019

Recently I have been working on a really simple case. When an HTTP server returned an error and a non-empty body, I needed to embed this body into an error structure. Although this is a simple case, I got a problem with implementing it in Mule 4. In the previous Mule edition, it was a little bit simpler. So let's see what it is all about.

Case

First, we have a look at the case that I have to implement. I have a mule application that is calling an external HTTP server via an HTTP request component. When the server responds with an error like 4xx, 5xx, and the returned body will is not empty, we would like to forward that response to the calling application.

Content Filter Pattern for REST Service — Implementation

In the last article, you can find the idea of how to introduce field filtering for your APIs. My simplified Content Filter allows for providing negative or positive filtering. The first one tells which fields Filter removes from the target response. The latter one tells which fields should be available in the response. Today I show you how I have implemented this using DataWeave language.

Filterable DataWeave Module

Okay, our input is straightforward. The Content Filter has two input arguments, like in the diagram below

Circuit Breaker Module

I guess that we more often think about our services in a “happy path” term, but we underestimate not so happy paths. What if my API is trying to reach another API/system and it is failing constantly? Can I reach it less often in case of a timeout? I thought about that in case of a Mule 4 application and I came up with Circuit Breaker pattern. In this article, I will briefly introduce the pattern and show you how you use it in your Mule application.

Circuit Breaker Pattern

Circuit Breaker monitors API calls. When everything is working as expected, it is in the state closed. When the number of fails, like timeout, reaches a specified threshold, Circuit Breaker will stop processing further requests. We call it the open state. As a result, API clients will receive instant information that something went wrong without waiting for the timeout to come.