@dnemoga/fetcher v1.3.0
@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 */ });
Fetcher Options
These options apply to every request outcoming from the current instance.
mode
(defaultcors
)credentials
(defaultsame-origin
)cache
(defaultdefault
)redirect
(defaultfollow
)referrerPolicy
(defaultstrict-origin-when-cross-origin
)
Making Request
fetcher.get('/resource', { /* Request Options */ })
.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 theGET
orHEAD
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
\ Thekeepalive
option can be used to allow the request to outlive the page. Fetch with thekeepalive
flag is a replacement for theNavigator.sendBeacon()
API.signal
\ AnAbortSignal
object instance; allows you to communicate with a fetch request and abort it if required via anAbortController
.
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)
});