Skip to content

Adding behaviour with middleware

berkeleybross edited this page Mar 23, 2021 · 2 revisions

Hippity is extremely customizable, since it uses Middleware to compose the request before it is actually sent. This let's you add global settings, such as auth tokens, to every request sent with the client. You can add behaviour such as retries, caching or even progress bars, or you can convert simple representations of data into something the server would understand. For instance, if you pass a Javascript object as the request body, it is converted to JSON by the Json Middleware - and likewise, the body is deserialized from json back into POJOs.

Defining custom middleware is extremely simple: it's a function which takes the current request and a callback to invoke the next middleware in the pipeline. You have to return the response of the request.

async function LoggingMiddleware(request, next) {
   console.log("Performing request")
   const response = await next() // or await next(newRequest) if you want to perform a different request. next can be called many times.
   console.log("Done")
   return response
}

To add your middleware to the client's pipeline, you call HttpClient.use(middleware). Each instance of a client is immutable - use() returns a new HttpClient which can be safely reused

const myClient = new HttpClient()
    .use(LoggingMiddleware) // It's important that you give it the function reference, don't call it yourself

Some middleware require context, e.g. a default setting. This can be achieved by creating a function which captures the parameter:

function BaseUrlMiddleware(defaultBaseUrl) {
   return async function(request, next) {
       return await next(baseUrl: defaultBaseUrl, ...request)
   }
}

const myClient = new HttpClient() {
    .use(BaseUrlMiddleware("http://example.com/")) // Here you call the function which returns the middleware that is passed to the HttpClient {
}
Clone this wiki locally