kwhitley / itty-durable

Cloudflare Durable Objects + Itty Router = shorter code
MIT License
236 stars 18 forks source link

Fix transformResponse #25

Open jacwright opened 1 year ago

jacwright commented 1 year ago

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 commented 1 year ago

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 commented 1 year ago

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
}