1

Javascript Fetch Wrapper

 1 year ago
source link: https://medium.com/@mylesdawson/javascript-fetch-wrapper-e9e6bdaeae1d
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Javascript Fetch Wrapper

1*qQ80J5LLtxG5yD_TuKdIbA.jpeg

Wrap fetch to improve developer velocity and avoid duplicate code. Handle the most common use-cases and errors when using fetch. Identify different fetch errors and handle them accordingly. Provided is a code snippet and below an explanation for its use.

Logger (line 1)

Your custom logger if you use one. Could be Sentry, an inhouse solution or in the worst-case just console.error

Allowed Fetch Methods (line 3)

Limit fetch methods allowed to prevent silly errors, can add additional methods if needed

Options (lines 5–8 and lines 12–15)

Optionally provide a body for POST/PUT requests and optionally override the default fetch method. Default body is null and the default fetch method is get

fetchWrapper (line 10)

Typescript users: Optionally provide generic argument for T if you know the response type. Pass the url you wish to fetch.

endpoint (line 17)

To avoid passing the base url everytime, combines the base url with the passed url. A base url might look like: https://google.com, the url might look like: /users/1/.

response (lines 19–26)

Pass arguments to fetch function and json-stringify the body. Include credentials to pass cookies along with requests. Captures fetch network exceptions immediately and logs it and throws an error on failure.

!response.ok (lines 29–42)

Try to decode the response data if possible otherwise fallback to predefined error message. Handle error code responses and throws an error.

data (lines 44–49)

Attempts to parse the json response, captures and throws an error on failure. Returns the data if parse was successful.

Step by Step

  1. Options are set to default values if none were provided
  2. The endpoint is created from a combination of the BASE_URL and the passed url
  3. The fetch function is configured with the endpoint and options. Catches , logs and throws an error on network exceptions
  4. If the response code is not within the “ok” range then try to decode response data. Log error, handle status code functionality and throw the error.
  5. Try to decode the json data response, log and throw an exception if it failed to parse json.
  6. Return the object data.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK