Skip to content
This repository has been archived by the owner on Jun 2, 2023. It is now read-only.

Fetch wrapper - handle both json & blob responses. #817

Open
barakyosi opened this issue May 26, 2020 · 0 comments
Open

Fetch wrapper - handle both json & blob responses. #817

barakyosi opened this issue May 26, 2020 · 0 comments

Comments

@barakyosi
Copy link

Hi Kent!

After reading your fetch wrapper blog, I implemented something similar in my project, something like:

export const fetchWithToken = (url, fetchData) => {
  return getCurrentToken()
    .then(({ token }) =>
      fetch(url, {
        ...fetchData,
        headers: {
          ...(fetchData && fetchData.headers),
          Authorization: `Bearer ${token}`,
        },
      })
    )
    .then(handleFetchErrors)
    .then(res => res.json());
};

Now there's a new requirement to add support for res.blob() for binary requests.
So the solutions I thought about were (roughly in order):

  1. Detect the response type based on response header. (not sure how, any suggestions?)
  2. Add "baseFetchWithToken" method that doesn't parse the response, moving responsibility to the consumer.
  3. Add a response-type argument (or create new fetchBlobWithToken method).
  4. Add try-catch, first trying to parse json response then parse blob response. (sounds awful, right? 😬)

Would be happy to hear your thoughts here :)

Thanks a lot for all you valuable content & teaching!

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant