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

Content-Type detection #567

Open
fregante opened this issue Mar 25, 2024 · 3 comments
Open

Content-Type detection #567

fregante opened this issue Mar 25, 2024 · 3 comments

Comments

@fregante
Copy link

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
Copy link
Author

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
Copy link
Owner

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

@fregante
Copy link
Author

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 #375

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

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

No branches or pull requests

2 participants