semantic-fetch
v0.2.0
Published
semantics redefined for the Fetch API
Downloads
3
Maintainers
Readme
Semantic Fetch
:tophat: A HTTP library with redefined semantics based on Fetch
The Fetch API is awesome, but it might need some tweaks when it comes to error handling and body resolving, this library provides an alternative fetcher with the following semantics:
- success means a response with status < 400
- failure results from a response with status >= 400, or a network error (status defined as 0)
- response comes with a body already resolved
Install
npm install semantic-fetch
It supports ES6 modules, AMD, CommonJS or a global variable as SemanticFetch
Getting started
// use fetch polyfill of your choice
// import 'isomorphic-fetch'
import 'whatwg-fetch'
import { createFetch } from 'semantic-fetch'
const fetcher = createFetch(fetch)
fetcher('/api', { method: 'GET' })
.then(res => {
// response body is available
console.log(`${res.status} ${res.body}`)
})
.catch(res => {
if (res.status === 0)
console.log('network error')
else
console.log(`failed due to ${res.body}`)
})
API
createFetch(fetch, bodyResolver)
Creates a fetch function
Arguments
this fetch creator takes 2 arguments:
fetch
(function)the Fetch function, you can inject a fetch implementation of your choice
bodyResolver
(function: Response => Promise) [Optional]a function that takes the response and returns a promise that resolves the body content, e.g.
res.json()
, a default bodyResolver is used if the arg is not provided
Returns
the enhanced fetch function that takes the same arguments as fetch
License
MIT