Useful JavaScript helper for creating HTTP requests and processing responses using JavaScript Fetch API.
I will share here a github gist that contains all the necessary code to easly use the Fetch API, a promised-based data fetching in plain JavaScript, to manage HTTP interactions in your frontend app.
1 – .then() or .catch()
Before showing you the code, it should be noted that, despite the fact that the Fetch API is a new powerful and flexible interface for fetching resources (compared to the old APIs like XMLHttpRequest), it comes with some drawbacks or let’s see a particular specification that differs from what we used to do before like with jQuery.ajax() ! The most important for me is :
The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
You can read more following this link Using Fetch. But if we come back to the specification above, i’ll say this could be inconvenient since some errors are resolved as a normal response, in other words, those errors are intercepted in the .then() function or the returned promise and not in the .catch(). In this helper all errors are rejected and so, are available in catch() function.
2 – .json() or .text()
I am also dealing with a somewhat particular case, that of empty responses returned from backend. In this case, if you would to allow this behavior, use .text() function intead of .json() to read the stream-based data of the response, otherwise you’ll get a confusing exception.
3 – Dev-friendly responses
Finally, this helper allow you to get Dev-friendly reponses, I mean you’ll have a same structure for all types of responses with two props headers and body. This is not the case with the Fetch API. On top of that, the responses are typed objects (classes) and you don’t have to do the hard work of checking status when processing a reponse, you can just some thing like that :if (response instanceof AppResponse)
/*this means there are no errors!*/if (response instanceof AppError)
/*this means there is an error!*//*AppError is base class of all errors classes*/if (response instanceof NotFoundError)/*this means that your AppError is a HTTP 404 Not Found error*/
4 – Code
You can see TypeScript version from here http_helper.js, where I used await/async and generics.
