Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
theuser47814yGood thing it doesn't. Fetching and parsing are two completely different operations.
-
They're not, at least in my experience.
Usually, I'll take the response and create a pipeline that allows for application-level interception handling of non-200 status codes, preflight token management, that sort of thing.
I also don't tend to use fetch directly in my component functions, class methods, etc. Instead I create a client module per service that abstracts away its usage so my consumer only ever sees the return type of the service itself. This becomes even nicer when blended with rxjs. -
Voxera113884yIts not and your solution would prevent future improvements and the possibility to use it with xml based api’s which is very common in government or enterprise solutions.
The goal of fetch is to do one thing and do it well, not to be a package deal.
If more developers thought in terms of Single Responsibility Principle we would generally have a much easier time reusing or extending existing solutions instead of working around bad design :) -
CptFox16164yIf that's your main use case, why not simply have your own function:
function fetchJson(url) {
return fetch(url).then(res=>res.json())
}
But I agree with @SortOfTested that you should have proper client functions to abstract away the request and parsing, and that way you can type check/hint the whole thing :D -
I'm just repeating what most people said - but in a less subtle way:
When you have sprinkled all your fetches and JSON parsing across the project, please burn it.
You have an API with defined endpoints. Based on one protocol with certain behaviour and limits.
You fetch from the API, expecting certain states and results.
The result is - again - expected to be valid JSON, parseable by an deserializer that has again certain behaviour.
And - again - you expect that deserializer to have a valid result - as in producing an object with certain fields and types, and as such behaviour.
Please. When you have an API - abstract it away and don't use it directly.
Prayers are for church, not for programming - expecting things to work is in programming a bad idea.
And yes, single responsibility principle is one thing.
But all in all (and this far exceeds SRP) is that a program shouldn't know what type of API it's talking to.
Input results in Error or Output. Nothing less, nothing more. Rest is hidden away so you can change it when it's necessary.
Related Rants
If 99% of fetch use case is fetch(url).then(r=>r.json()), API should have been fetch.json(url)
rant
http requests
json
api
fetch