After doing the following, you can simply call UserRepository.getProfile() to receive the Promise returning User object.
HttpClient Options
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:
import { HttpFetch, HttpCode, ResponseError, NormalizedHttpOptions } from'@coolio/http';exportconsterrorInterceptor= <Body>( request:HttpFetch<Body>, options:NormalizedHttpOptions,):HttpFetch<Body> => {return () =>request().then(response => {// You can always use `HttpCode` enum as in this case, however// `response.status < 400` would be better in this caseif(response.status ===HttpCode.OK){return response; }thrownewResponseError(response); })};// In your httpClient.ts add the following:httpClient.addInterceptor(errorInterceptor);
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 add Authorization header in your authInterceptor.
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:
npminstall@coolio/json-api# or if you're using fancy stuff:yarnadd@coolio/json-api
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.