Small fetch wrapper for creating quick API wrappers
npm i -D @sampullman/fetch-api
yarn add @sampullman/fetch-api
pnpm i -D @sampullman/fetch-api
FetchApi
global configuration is passed to the constructor.
FetchApi({
// API base URL prepended to requests
baseUrl: '',
// Default request timeout
timeout: 10000,
// Passed to JSON.stringify and used as fetch `body`.
// Sets headers: { Accept: 'application/json', 'Content-Type': 'application/json' }
data: null,
// Request URL parameters, e.g. `{ 'a': 1 }`. Passed to `new URLSearchParams(params)`
// Entries with undefined values are filtered out
params: RequestParams,
// Convenience for Basic Auth.
// Sets headers['Authorization'] = `Basic ${btoa(`${auth.username}:${auth.password}`)}`
auth: { username: 'test', password: 'password' }
// Request interceptors
requestInterceptors: [],
// Response interceptors
responseInterceptors: [],
});
Here is an example of basic usage that includes a response interceptor for handling 403 response codes and converting the body to json.
const api = new FetchApi({
baseUrl: 'https://cool.api/',
responseInterceptors: [
async (res) => {
const { status } = res;
if (status === 403) {
throw new Error('FORBIDDEN');
}
res.data = await res.json();
return res;
},
],
});
// Make a get request to 'https://cool.api/status/'
const status = api.request({ url: 'status/' });
fetch
must be available. If you need to support older browsers or Node, use a polyfill such as whatwg-fetch
See the example
directory.
MIT License © 2021 Samuel Pullman