sindresorhus / ky

🌳 Tiny & elegant JavaScript HTTP client based on the browser Fetch API
MIT License
11.83k stars 341 forks source link

Content-Type detection #567

Closed fregante closed 3 weeks ago

fregante commented 3 months ago

I'm manually doing content detection:

const response = await ky
  .post(tokenURL, {
    body: formData,
  })

switch (response.headers.get("Content-Type")) {
  case "application/json": {
    const parsed: AuthData = await response.json();
    // etc
  }

  case "application/x-www-form-urlencoded": {
    const parsed = await response.formData();
    // etc
  }

  default: {
    throw new TypeError(
      "Error getting OAuth2 token: unexpected response format",
    );
  }
}

Would it make sense to have an .auto() parser that deals with the content type automatically? JSON, FormData, Blob, etc. I think that's what Axios does for example (but it returns unknown as a type)

fregante commented 3 months ago

I don't know if it would bring substantial code improvements over the above code, but it would avoid having to figure out the various Content-Type strings

sindresorhus commented 3 months ago

How common is it to not know upfront what type you will be receiving? What is the use-case for such a thing?

fregante commented 3 months ago

Not very.

This specific scenario could be because it's a user-provided API endpoint. In reality APIs can also return "the wrong type", as seen in https://github.com/sindresorhus/ky/issues/375

So for example .auto() could handle both a proper JSON response and raw text, both of which would eventually be a valid "JsonValue"