🥖Fetch Wrapper

A fetch wrapper is a piece of code that wraps the JavaScript fetch() function, which is used to make HTTP requests. It typically provides a simpler, more convenient interface for making common types of requests, such as GET, PUT, POST, and DELETE.

Here is an example of a fetch wrapper that provides these four methods:

class FetchWrapper {
  constructor(baseUrl) {
    this.baseUrl = baseUrl;
  }

  async get(url) {
    const response = await fetch(`${this.baseUrl}${url}`);
    return response.json();
  }

  async put(url, data) {
    const response = await fetch(`${this.baseUrl}${url}`, {
      method: 'PUT',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json',
      },
    });
    return response.json();
  }

  async post(url, data) {
    const response = await fetch(`${this.baseUrl}${url}`, {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json',
      },
    });
    return response.json();
  }

  async delete(url) {
    const response = await fetch(`${this.baseUrl}${url}`, {
      method: 'DELETE',
    });
    return response.json();
  }
}

const fetchWrapper = new FetchWrapper('https://my-api.com');

// GET request
fetchWrapper
  .get('/users')
  .then((users) => console.log(users))
  .catch((error) => console.error(error));

// PUT request
fetchWrapper
  .put('/users/1', { name: 'John', age: 30 })
  .then((user) => console.log(user))
  .catch((error) => console.error(error));

// POST request
fetchWrapper
  .post('/users', { name: 'Jane', age: 25 })
  .then((user) => console.log(user))
  .catch((error) => console.error(error));

// DELETE request
fetchWrapper
  .delete('/users/1')
  .then((user) => console.log(user))
  .catch((error) => console.error(error));

In this example, the FetchWrapper class has a constructor that takes a base URL as an argument. It then provides four methods for making GET, PUT, POST, and DELETE requests using the fetch() function. Each method returns a Promise that resolves with the JSON response from the server.

Last updated