Simple Fetch API wrapper that tries to address most of its annoyances

Would be awesome to get an honest review of this npm package, FarFetch. Here’s a demo to show how easy it is to upload files with this Fetch API wrapper.

async function uploadFiles() {
  const files = document.querySelector('#my-files').files;

  await ff.post('https://website.com/people', {
    files,
    data: { name: 'Vicky', age: 28 },
  });
}
1 Like

It looks pretty good, except for this line:

if (response.status !== 200) throw new FarFetchError('Server error.');

You’re throwing an error on anything that’s not 200, except anything that’s 2xx is a good response. I probably use 204 (no content) just as much as 200.

Fetch actually includes this check out of the box, so you don’t have to do status >= 200 && status < 300 you can just say response.ok, which is a boolean.

You should consider adding the status code to the fetch error as well. Since you’re creating your own error, then you can just add that to it as a class property. It would be nice to know the difference between a 400 and a 500, for instance. 3xx are server actions, 5xx are server errors, and 4xx are client errors.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

I didn’t really look too deep into it beyond what I mentioned here, but it looks pretty good! I really like the beforeSend and afterSend hook concept.

1 Like

Thanks so much for the feedback!

You’re throwing an error on anything that’s not 200, except anything that’s 2xx is a good response. I probably use 204 (no content) just as much as 200.

I will change it to response.ok. Thanks for the catch.

You should consider adding the status code to the fetch error as well. Since you’re creating your own error, then you can just add that to it as a class property. It would be nice to know the difference between a 400 and a 500, for instance. 3xx are server actions, 5xx are server errors, and 4xx are client errors.

Actually, the way I have setup is that I pass in { response, error }. So you can use the native response to check

Oh cool! I missed that. Thanks for the clarification.

Thank you for taking the time to give me suggestions again. I really appreciate it. Also, I just updated my package to check for response.ok, instead of just 200.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.