Strategy Role-playing game example

Here is an example of how a fetch wrapper might be used in the context of a strategy role-playing game:

// game-api.js

class GameAPI {
  constructor() {
    this.baseUrl = 'https://my-game-api.com';
  }

  async getEnemies() {
    const response = await fetch(`${this.baseUrl}/enemies`);
    return response.json();
  }

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

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

  async deleteEnemy(id) {
    const response = await fetch(`${this.baseUrl}/enemies/${id}`, {
      method: 'DELETE',
    });
    return response.json();
  }
}

// game.js

import { GameAPI } from './game-api';

class Game {
  constructor() {
    this.api = new GameAPI();
  }

  async start() {
    console.log('Loading enemies...');
    const enemies = await this.api.getEnemies();
    console.log(enemies);

    console.log('Creating enemy...');
    const enemy = await this.api.createEnemy({ name: 'Orc', level: 1 });
    console.log(enemy);

    console.log('Updating enemy...');
    const updatedEnemy = await this.api.updateEnemy(enemy.id, {
      name: 'Orc Chief',
      level: 2,
    });
    console.log(updatedEnemy);

    console.log('Deleting enemy...');
    await this.api.deleteEnemy(updatedEnemy.id);
  }
}

const game = new Game();
game.start();

Last updated