Getting Started
HTTP
A simple HTTP client for web apps. Supports interceptors & global configuration.
Quick start
Installation:
Initialize a HttpClient and configure it as below:
Use the client in repositories containing API bindings:
After doing the following, you can simply call UserRepository.getProfile()
to receive the Promise returning User
object.
HttpClient Options
Parameter
Required
Description
baseUrl
no
Base path for making all relative requests.
requestHandler
yes
Abstraction layer for the standard fetch
mechanism or any other transport you can think of. By default you can use fetchRequestHandler
, which uses fetch
underneath. You can also use built-in mockRequestHandler
for testing purposes or httpRequestHandler
from @coolio/http-request-handler
.
defaultHeadersProvider
no
Function returning common headers for all request sent by your client. Host argument can be used to pass authorization data, but only for specific domain.
bodyParser
no
Adds a custom parser that processes the response body. Parsed body can be always accessed via parsedBody
Promise in HttpResponse
. By default it returns an ArrayBuffer
. If you pass the standard bodyParser
, it will decode JSON, URL-encoded body and plain text responses. It also supports case conversion, which is useful if your API returns responses in a convention that doesn't match your needs.
bodySerializer
no
Adds a custom serializer that can process body before sending. It supports case conversion.
Interceptors
Quite often we need to do something "in-between" while our API requests are running. This is why we have a built-in interceptors mechanism. They can:
throw errors if response status code indicates that request failed,
automagically retry request up to X times if it failed,
transparently reauthorize if your access token has been revoked
The first case is described below:
As you can see, interceptors accept two arguments:
HttpFetch
- a function that returns a Promise that performs http request. It allows to queue or delay multiple requests, retry them etc.NormalizedHttpOptions
- options that can be modified before request is made, i.e. you can addAuthorization
header in yourauthInterceptor
.
Advanced Use Cases
If you happen to use JSON API, you may benefit from using a wrapper library that handles most of it's specs:
See @coolio/json-api's README.md for details.
Last updated