-
Notifications
You must be signed in to change notification settings - Fork 0
Default middleware and clients
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.
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.
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.
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).
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.
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, */*' },
})
)