Created
September 22, 2023 15:10
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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