whatwg / fetch

Fetch Standard
https://fetch.spec.whatwg.org/
Other
2.1k stars 326 forks source link

Add Fetch Assertions #1683

Open shgysk8zer0 opened 1 year ago

shgysk8zer0 commented 1 year ago

As an extension and counter to #1679 I propose adding fetch assertions.

Example

try {
  const resp = await fetch(url, {
    headers: { Accept: 'application/json' },
   assert: {
     ok: true,
     acceptable: true,
     /* ... */
    }
  });
  // Handle response, knowing already it's `ok` and JSON (per Accept and Content-Type headers)
} catch(err) {
  // Handle error
}

Reasoning

jakearchibald commented 1 year ago
  • Many devs (esp inexperienced) assume fetch() throws under conditions in which it does not

That means developers need to learn to look at the response before assuming it's ok, or they need to learn to correctly use your proposed configuration options. Those feel of similar complexity.

The current system of checking response.ok means you can use the response if it isn't ok. Whereas that isn't the case with this proposal.

The acceptable option could be split out as response.assertAcceptable(), which is more composable as you can check response.ok and response.assertAcceptable() separately, and react differently to each case.

However, "does the server say the response is JSON?" seems much less useful than "does the response parse as JSON?". If I'm expecting JSON, having a response that parses as JSON seems like a stronger signal that I'm getting what I expect than taking the server's word for it.