Skip to content

Instantly share code, notes, and snippets.

@SlideeScherz
Created September 22, 2023 15:10
Show Gist options
  • Save SlideeScherz/fed4da306635e2c22999b2018869ec26 to your computer and use it in GitHub Desktop.
Save SlideeScherz/fed4da306635e2c22999b2018869ec26 to your computer and use it in GitHub Desktop.
Parse a Response object by its content type, to avoid a JSON.parse error
const parseByContentType = async <T = unknown>(data: Response): Promise<T> => {
const contentType = data.headers.get('Content-Type');
if (contentType === null) {
console.log('contentType is null');
return (await data.text()) as T;
} else if (contentType.includes('application/json')) {
return (await data.json()) as T;
} else if (contentType.includes('text')) {
return (await data.text()) as T;
// add other cases as needed
} else {
console.log(`contentType: ${contentType} not handled`);
return (await data.text()) as T;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment