Skip to content
This repository was archived by the owner on Jun 17, 2024. It is now read-only.
This repository was archived by the owner on Jun 17, 2024. It is now read-only.

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

@barakyosi

Description

@barakyosi

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!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions