Fetch wrapper - handle both json & blob responses.
Opened this issue · 0 comments
barakyosi commented
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):
- Detect the response type based on response header. (not sure how, any suggestions?)
- Add "baseFetchWithToken" method that doesn't parse the response, moving responsibility to the consumer.
- Add a response-type argument (or create new
fetchBlobWithToken
method). - 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!