Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix transformResponse #25

Open
wants to merge 1 commit into
base: v1.x
Choose a base branch
from
Open

Conversation

jacwright
Copy link
Contributor

The transformResponse fails for invalid JSON. Because it wasn't async, it would always return the promise from the response.json() call. Making it async allowed it to fail the JSON and move on to the next step, but because the body was already read/parsed, the response.text() would always fail. So we have to read the text first, then try and parse it as JSON. If it is JSON, return it. If not, return the text. If reading the text failed, return a response.

The `transformResponse` fails for invalid JSON. Because it wasn't async, it would always return the promise from the response.json() call. Making it async allowed it to fail the JSON and move on to the next step, but because the body was already read/parsed, the response.text() would always fail. So we have to read the text first, then try and parse it as JSON. If it is JSON, return it. If not, return the text. If reading the text failed, return a response.
@kwhitley
Copy link
Owner

kwhitley commented Jan 9, 2023

Looks like this collides with my latest (websocket support) that might better address this (by not brute forcing a double-parse attempt like I previously did):

// helper function to parse response
const transformResponse = response => {
  const contentType = response.headers.get('content-type')
  try {
    if (contentType.includes('json'))
      return response.json()
  } catch (err) {}

  try {
    if (contentType.includes('text'))
      return response.text()
  } catch (err) {}

  return response
}

You see any issues with that? My concern with doing it the way you and I (previously) both did, is if someone actually for some reason wanted to send valid JSON as plain text for some reason. I mean, I doubt it would happen but... it's possible?

@kwhitley
Copy link
Owner

kwhitley commented Jan 9, 2023

Conversely we could also blend the two:

// helper function to parse response
const transformResponse = async response => {
  const contentType = response.headers.get('content-type')
  let body

  try {
    if (contentType.includes('json')) {
      body = await response.json()
    } else if (contentType.includes('text')) {
      body = await response.text()    
    }

    return body
  } catch (err) {}

  return response
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants