navio / smallfetch

Small Fetch is a pre-configured Fetch factory that provides an object ready to consume Rest API. It sets the headers and parse the response to JSON. It handle errors and can cancel request on fly. 🐶

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool


NPM Version Size

smallfetch

Smallfetch is a pre configured fetch object ready to interact with a Rest API

Tiny implementation of 200B with no dependencies.

  • It sets headers by default to 'application/json'.
  • It stringify object payload and pass it as body content for PUT/POST/PATCH.
  • It parses server response to JSON.
  • It throws a cachable error when the response is not in the range 200-299.

Installation

npm install smallfetch
import sf from 'smallfetch';

Usage

Get - Search

let books = await sf('https://example.com/books');
console.log(books);

Post - Create

sf('https://example.com/books','POST',{name:'Book Name',desc:'Description'})
.then(response=>console.log(response))
.catch(error=>console.log('something is wrong',error));

Put - Update

sf('https://example.com/books/1','PUT',{name:'Book Name',desc:'Description'})
.then(response=>console.log(response))
.catch(error=>console.log('something went wrong',error));

To avoid throwing errors (for parallel request) pass false at the end of the request.

Promise.all([
sf('https://example.com/books/1','POST',false),
sf('https://example.com/books/2','POST',false),
sf('https://example.com/books/3','POST',false)
]).then(results=>{
	results.forEach(result=>console.log(result))
});

All request will execute without failing. If the request fail an object with the request data will be returned but no exception will be thrown.

About

Small Fetch is a pre-configured Fetch factory that provides an object ready to consume Rest API. It sets the headers and parse the response to JSON. It handle errors and can cancel request on fly. 🐶

License:MIT License


Languages

Language:JavaScript 100.0%