@dnemoga/fetcher
A minimalistic library built around the native Fetch API with zero dependencies.
Getting Started
Installation
npm install @dnemoga/fetcher
Importing
import { Fetcher } from '@dnemoga/fetcher';
Creating Instance
const fetcher = new Fetcher({ });
Fetcher Options
These options apply to every request outcoming from the current instance.
Making Request
fetcher.get('/resource', { })
.then(console.log, console.error);
| Note: Supported methods are get
, head
, post
, put
, patch
, and delete
.
Request Options
-
data
Any body that you want to add to your request. Note that a request using the GET
or HEAD
method cannot have a body.
-
params
Any search parameters you want to add to your request, contained within an object literal with string values.
-
headers
Any headers you want to add to your request, contained within an object literal with string values. Note that some names are forbidden.
-
integrity
Contains the subresource integrity value of the request.
-
keepalive
The keepalive
option can be used to allow the request to outlive the page. Fetch with the keepalive
flag is a replacement for the Navigator.sendBeacon()
API.
-
signal
An AbortSignal
object instance; allows you to communicate with a fetch request and abort it if required via an AbortController
.
Next Steps
Interceptors
onRequest.use()
const customHeaders = async (request) => {
request.headers.set('X-Foo', 'Foo');
request.headers.set('X-Bar', 'Bar');
return request;
};
fetcher.onRequest.use(customHeaders);
onRequest.eject()
fetcher.onRequest.eject(customHeaders);
onResponse.use()
const errorHandler = async (response) => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response;
};
fetcher.onResponse.use(errorHandler);
onResponse.eject()
fetcher.onResponse.eject(errorHandler);
Request Timeout
fetcher.get('/resource', {
signal: AbortSignal.timeout(30000)
});