Skip to content

Instantly share code, notes, and snippets.

@Noitidart
Created February 25, 2018 17:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Noitidart/89b660bd9d212d926ee4848b8af0f18d to your computer and use it in GitHub Desktop.
Save Noitidart/89b660bd9d212d926ee4848b8af0f18d to your computer and use it in GitHub Desktop.
_js-getResponseAsJsonOrText.js - Sometimes even if response.headers.contentType is json it is not in proper json format, so we should return text, but doing response.json() and then trying respone.text() even if response.json() fails - gives "TypeError: Already read" which means body consume, so I have to do it this way.
// figure out if response is json or text
const { status, headers:{map:{'content-type':[contentType]}} } = res;
const isJson = contentType && contentType.includes('json');
let reply = yield call([res, res.text]);
if (isJson) {
try {
reply = JSON.parse(reply);
}
catch(ignore) { console.log('failed to turn to json, Content-Type said it was json, contentType:', contentType) }
}
// try {
// reply = yield call([res, res[isJson ? 'json' : 'text']]);
// } catch(ex) {
// console.log('ex when trying to get res:', ex);
// if (isJson) {
// console.log('was json but failed, so will try text');
// try {
// // this fails with "TypeError: Already read" - so i just do the read to text always, then if isJson try parsing it
// reply = yield call([res, res.text]);
// } catch(ex2) {
// console.log('still ex when trying to do res.text, ex2:', ex2);
// // leave it at undefined
// }
// }
// // else leave it at undefined
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment