If 99% of fetch use case is fetch(url).then(r=>r.json()), API should have been fetch.json(url)

  • 8
    Good thing it doesn't. Fetching and parsing are two completely different operations.
  • 3
    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.
  • 4
    Its 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 :)
  • 5
    If 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
  • 3
    My spam bot is not interested in the result. Parsing is wasted cpu time!
  • 3
    @KDSBest the you agree that a function doing both is wrong :P
  • 1
    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.
  • 0
    Nobody stopped you from creating your own prototype function
  • 0
Add Comment