Created
February 25, 2018 17:05
-
-
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.
This file contains 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
// 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