Skip to content

Default middleware and clients

berkeleybross edited this page Mar 23, 2021 · 1 revision

By default, the HttpClient can't actually do anything - you must register all middleware used by your application, including the middleware which actually performs the HttpRequest. For convenience, Hippity provides two default clients which you can extend - if you don't use them, they should be tree-shaken.

Included Middleware

sendTerminator, requestTerminator, xhrTerminator

These perform the HTTP request, and at least one terminator should be used. They are called terminators because they don't call "next" and, in effect, terminate the pipeline.

The requestTerminator uses node's "request" object to perform the request. The xhrTerminator uses the client's "xhr" object to preform the request. The sendTerminator detects if it is running in node or in a browser, and delegates to either the requestTerminator or xhrTerminator. This should be the default option, if you are unsure.

transformMiddleware

This middleware makes writing other, simple middleware easier to write! You may want to implement some middleware which only transforms a request to another request and doesn't care about the response, for example adding a default auth header to all requests. For these simple situations, you can write a "requestTransform" or "responseTransform", and give them to the transformMiddleware.

defaultHeadersMiddleware

Adds a collection of default headers depending on the request method. Default headers will not be applied if the request has explicitly added it's own value (or explicitly removed it by setting the header to null).

userAgentMiddleware

Adds "hippity/{version}" as the user agent. This should not be used client side, since browsers don't let you to change the user agent. It's optional when not in the browser, but it's recommended to use it because some servers are misconfigured and require a useragent.

resolveUrlInMethodPropertiesMiddleware

jsonMiddleware

timeoutMiddleware

Included transforms

basicAuth

defaultHeaders

baseUrl

Default clients

export const httpClient = new HttpClient()
  .use(sendTerminator())
  .use(timeoutMiddleware())
  .if(isNode, (c) => c.use(userAgentMiddleware()))
  .use(resolveUrlInMethodPropertiesMiddleware())

export const jsonClient = httpClient.use(jsonMiddleware()).use(
  defaultHeadersMiddleware({
    common: { accept: 'application/json, text/plain, */*' },
  })
)