Interceptors - don't repeat yourself

Smiley faces repetition

How to solve repetition problem in HTTP clients

One of my colleagues opened the following MR. Merge request with repetition

The first thing that catches the eye is the most common programming smell - repetition. Merge request with repetition marked

One way to handle it is to move the repetition into a separate method. Repetition extracted to a method

And call it in each of the get methods. Extracted method called in other places

But again - repetition. Each new method still has duplicated code. Extracted method called in other places repetition marked

The solution here is to use an interceptor. An interceptor allows you to modify a request before it's executed or a response before it's returned. To solve the repetition problem, we'll use the request interceptor. We'll move the authorisation logic to an interceptor. Authorisation logic moved to a request interceptor

Now we can remove the repetition from the client. Authorisation logic moved to a request interceptor

Et vuala. No more repetition.

Interceptors have many use cases. Based on my experience, setting a header is the most common one.

Other common use cases are:

  • Logging request/response
  • Retrying a request on error with a backoff strategy
  • Error mapping