2.0.1 • Published 5 years ago
fetchz v2.0.1
fetchz
A lightweight wrapper (only 823B gzipped!) over fetch api to make fetch calls easier without boilerplate code! Abortable fetch with timeout, internal response.ok handling, configuration and utility functions for http methods.
Features
- Check for response.ok errors
- Each request has an abort method
- Timeout setting for requests
- Settings config for BaseUrl and Authentication token
- Util functions for HTTP request methods
Installing
npm install --save fetchz
Example Usage
Import:
import fetchz from 'fetchz';
Setting configuration:
// set baseUrl (default is application origin)
fetchz.config.BASE_URL = 'https://my-app.com/'
// set request timeout in ms (default is 5000ms)
fetchz.config.TIMEOUT = 7000;
// set token get method
fetchz.config.TOKEN = () => localStorage.getItem('jwt');
// set authorization type
fetchz.config.AUTH_TYPE = 'Basic';
Example POST request:
// JSON.stringify will be automatically used on body if no Content-Type header is specified
try {
const request = fetchz.post('post-route', {
body: {
foo: 'bar'
}
}).then(response => response.json())
.then(json => {
const data = json;
})
// catch block will also return any non 200 response errors as well as timeout errors
} catch (error) {
console.error(error);
}
// Aborting request
request.abort();
Passing route:
// request to base url / route
fetchz.get('route');
// request to app origin / route
fetchz.get('/route');
// request to route
fetchz.get('https://api/route');
Work in Progress:
- Instance creation
Cancel method- Response/request interceptors