rd-fetch
A developer friendly fetch wrapper class.
What this do?
When trying to migrate across from ajax, I found the way fetch handled HTTP response codes to be a bit confusing, especially for what would usually be considered errors. I found it doubly confusing trying to handle json response payloads for errors. So I made this wrapper to make things a little more convenient.
Currently this only really supports JSON, but there's no reason it couldn't support other data/content types as well.
Installation
npm i -S rd-fetch
Tests
npm run test
Usage
rd-fetch
exports a class Fetch
which contains static methods for making different kinds of requests. So all you need to do is
;
Then call the static method you need passing the required arguments to send your request.
Methods
Fetch.json
Fetch.json
is a static method that will handle communicating with a resource via json. If the request status is ok, (ie., response.ok
) you will be able to do what you want with the response
in your then
. If the request status is not ok, a rejected promise will be returned allowing you to catch the response
payload in your catch
. In both instances, the response
will have a json
property attached to it.
; Fetch ;
Arguments
url
The URL to fetch
options
The options to use with the fetch.
options.method
The method to use, defaults to GET
.
options.headers
The headers to use, defaults to
'Accept': 'application/json' 'Content-Type': 'application/json'
options.body
The body to send, defaults to null
. Fetch.json
will auto JSON.stringify
this option so you should pass a standard JavaScript object for this option.
Advanced Usage
Since fetch calls return promises, you can handle default and custom behaviour pretty nicely by wrapping a call to a Fetch
static method in a function that returns it like so
const log = responses: errors: ;let user; /** * General use request method. Pushes responses/errors into a log. * Always returns a promise. * * @param * @param * @return */ { return Fetch ;} /** * Logs the user in. Sets user data. * * @param * @return void */ { ;}
License
Credits
rd-fetch
was built by rohan-deshpande with