A thin wrapper over fetch, used to specify common request and response processing in a single location.
Special thanks to Remerge for open sourcing this library.
Motivation
The Fetch API covers about 90% of the use cases that most existing HTTP client libraries exist to address. However, in practice you often want to handle all of an application's requests the same way, coupled to application state (like authentication credentials). This library exists to solve that problem.
Many of the existing implementations also offer extensive APIs for common scenarios, with fluent interfaces and lots of methods. This library aims to do the opposite, offering the minimum surface area capable of addressing all typical application scenarios.
In particular this library aims to offer an API whose usage can be verified through static analysis, so the utility functions offered here are all named exports, they never mutate their inputs, and they're stateless. In other words, aim to be unbreakable.
Usage
import { createFetch, prependHost, addHeaders, processBody, rejectIfUnsuccessful } from '@remerge/http-client'; import store from 'my-application-state'; const fetch = createFetch({ requestReducers: [ prependHost(process.env.API_HOST), addHeaders({ Accept: 'application/vnd.api+json', 'Content-Type': 'application/json', }), addHeaders(() => store.getAuthorizationHeaders()), processBody(JSON.stringify), ], responseReducers: [ rejectIfUnsuccessful, response => response.json(), ], }); fetch('/profile');
This defines a client which will prepend the process.env.API_HOST host to incoming request URLs, add default content type headers and authorization headers from the application store and send the request body as a JSON string.
Responses with a non-successful status code will cause the Promise chain to reject, and will otherwise be unwrapped, returning only the parsed JSON body of the Response.
Installation
Available as an NPM exporting a UMD module.
# npm install micro-http-client
yarn add micro-http-clientReducers
A reducer is a function which takes a request or response object and returns a new object. Each will be called in turn to set up the request before it's passed to global.fetch(), and process the response once it's received.
Reducers may return a Promise.