Middleware-Pipelines

Middleware Pipelines - Promises

Middleware Pipelines - Promises

I’ve been looking at the possibilities of a simple middleware pipeline script. So far I’ve implemented a version of the Chain of Responsibility pattern. I’ve also been looking at using the same builder to work with promises. Here is what I’ve found.

Fetching some data from an API

So for this example I will define a few interfaces defining the data I am working with.

The context for each middleware function is going to be an object with a request and a response. This means that the middleware can work with either during each step.

Middleware Pipelines - Chain of Responsibility

Middleware Pipelines - Chain of Responsibility

Out of curiosity, I’ve been experimenting with what you can do with a simple and generic middleware builder. I’ve been surprised at how powerful it can be with such a small amount of code.

A simple but powerful function

I did a lot of reading, and gained a fair amount of inspiration from researching various implementations of the Chain of Responsibility pattern along with diving into the express.js and redux codebases.

It has essentially boiled down to using reduceRight on an array of functions. The following code has simplified types to make it easier to read but shows the concept.