JSON Fetch Talker
Easy way to send request for a json and control response (using fetch).
Features:
- send get/post request (as
FormData
) - handle network errors
- handle non-json format as an error
- use response via
callback
orerrorsHandler
Dependencies:
- whatwg-fetch -
fetch
polyfill - promise-polyfill -
Promise
polyfill - query-converter - query url converter
Install
npm install json-fetch-talker
Usage
tl;dr
let talker = let formData = name: 'User Name' email: 'user@email.com'talker
Import class
Create an instance (passing options or not)
let talker = options
You can override all default options:
defaultOptions = useCatch: false errorsHandle: true { } fetchCredentials: 'same-origin' fetchMode: 'same-origin' fetchCache: 'no-cache' fetchRedirect: 'error' fetchHeaders: key: 'X-Fetch-Request' value: true
.get()
or .post()
methods.
Create requests with Both methods receive ( url: string [, body: object, callback: function, errorsHandler: function] )
calback
responds with ( payload: object, response: Response, responseBody: string )
errorsHandler
responds with ( message: string, payload: object, response: Response, responseBody: string)
Both methods return Promise
For example:
talker talker
Options
bool - (true|false)
useCatch: Whether to use .catch()
on response. Default - false
.
bool - (true|false)
errorsHandle: Whether to handle errors or conceal failed requests. Default - true
.
function(message:string)
errorsHandler: You can use your own handler for errors! It is a 'global' errors handler for this instance of JSON_Talker, but you can redeclare it in one exact call.
string - (omit|same-origin|include)
fetchCredentials: Native credentials
option. Sending cookies and header. Default - same-origin
string - (same-origin|no-cors|cors)
fetchMode: Native mode
option. Cross-domain mode. Default - same-origin
string - (default|no-store|reload|no-cache|force-cache|only-if-cached)
fetchCache: Native cache
option. Cache type header. Default - no-cache
string - (follow|error)
fetchRedirect: Native redirect
option. Whether to follow redirect or create an error. Default - error
Caveat: Using both useCatch:false
and fetchRedirect:'error'
will cause unhandled response error
array
fetchHeaders: Array of objects
, representing headers, that will be sent with the request. Each object
should have key
and value
elements.