JavaScript Tutorial
  • 🍼Introduction
  • 🥛Hello Gamers
  • 🍯Variables
    • Action Game Example
  • 🌰Strings
    • RPG Example
  • 🍪Character Acces
    • Simulation Example
  • 🍩Plus (+) operator
    • Strategy Game Example
  • 🥜Functions
    • Adventure Game Example
  • 🍿Template strings
    • Strategy Game Example
  • 🍫Numbers
    • Sports Game Example
  • 🍬Converting Numbers to Strings
    • Fighting Game Example
  • 🍭Operations
    • FPS Game Example
  • 🍮Conditions
    • Platformer Game Example
  • 🎂Arrays
    • Puzzle Game Example
  • 🍰Objects
    • Racing Game Example
  • 🧁Arrow Functions
    • Rhythm Game Example
  • 🔌Shameless Plug
  • 🥧Implicit Return
    • Platform Game Example
  • 🍦String Methods
    • GRID Game Example
  • 🍨Object Literals
    • Board Game Example
  • 🍧DynamicProperty
    • Political Game Example
  • 🍡Reading Dynamic Property
    • Hide & Seek Game
  • 🥮Objects Continued
    • Medieval Game Example
  • 🥠Object Shorthands
    • Trivia Game example
  • 🔌Shameless Plug (again)
  • 🍥Destructuring & Concatenation
    • Dig a hole game example
  • 🍏Optional Chaining
    • Action Game Example
  • 🍐Nullish coalescing operator
    • Adventure Game Example
  • 🍊Refactoring If Conditions
    • Arcade Game Example
  • 🍋Implicit Conversion & Falcy Values
    • Strategy Game Example
  • 🍌Arrays of objects
    • Sports Game Example
  • 🍉Transforming Array of Objects
    • Fighters Game Example
  • 🍇Some important array methods
    • FPS Example
  • 🫐Reducing arrays of objects
    • Third Person Shooter Example
  • 🍓Try....catch
    • Platformer Example
  • 🍈Immutability
    • Puzzle game example
  • 🍒Creating new arrays or objects
    • Racing Game Example
  • 🔌Shameless Plug (again)
  • 🍑Immutable object operations
    • Basics
    • Rhythm Game Example
  • 🥭Classes
    • Basics
    • Platformer Game Example
  • 🍍Instance Method
    • Basics
    • Role-playing game example
  • 🥥Object Oriented Programming
    • Basics
    • Stealth Game Example
  • 🥝Getters & Setters
    • Basics
    • Survival Game Example
  • 🍅Static Methods & Chaining
    • Basics
    • Tactical Role Playing Game
  • 🍆Class Inheritance
    • Tower Defense Game Example
  • 🥑Use of Super
    • Vehicular Combat Game example
  • 🫒Public Class Field
    • MMORPG Example
  • 🥦Private class fields
    • Battle Royale Games Example
  • 🥬Aysnc/Await
    • Collectible Card Game example
    • Video Board game example
  • 🫑SetTimeout
    • Dice game example
  • 🥒Execution Order
    • Digital Collectible Card Game example
  • 🌶️The callback pattern
    • Life Simulation Game example
  • 🌽Promises
    • Music Game Example
  • 🥕Writing a function that returns a promise
    • Party game example
  • 🧄Introduction to JSON
    • Tile based game example
  • 🧅JSON.parse(string) / JSON.stringify(object)
    • Rhythm action game example
  • 🍠JSON Example for a game
    • Fetching JSON game data
  • 🥐Handling fetch errors
    • Fetch and HTTP Requests
  • 🥯ES Modules
    • Tower Defence Game Example
  • 🍞Default Export
    • Strategy Adventure Game Example
  • 🥖Fetch Wrapper
    • Strategy Role-playing game example
  • 🔌Final Shameless Plug
  • 🫓Lexical Scope and Arrow Functions
    • Vehicular Combat Game Example
  • 🥨Passing Functions
    • Vehicular simulation game example
  • 🥚Dynamic Imports
    • Video card game example
  • 🍠What is a closure
    • Video casino game example
  • 🎆Congratulations
Powered by GitBook
On this page

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.

PreviousStrategy Adventure Game ExampleNextStrategy Role-playing game example

Last updated 2 years ago

🥖