From 4ee3d0b39a01cfe4837e63b40eef05484259e981 Mon Sep 17 00:00:00 2001 From: GRZ4NA Date: Sun, 3 Oct 2021 16:03:36 +0200 Subject: [PATCH] created API Client --- src/constants.js | 5 +++++ src/utils/APIClient.js | 24 ++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 src/utils/APIClient.js diff --git a/src/constants.js b/src/constants.js index 1cc4696..419ca5a 100644 --- a/src/constants.js +++ b/src/constants.js @@ -1 +1,6 @@ +import { createContext } from "react"; +import { APIClient } from "./utils/APIClient"; + export const BACKEND_URL = "http://localhost:3000"; +export const EVENT_CONTEXT = createContext([]); +export const API_CLIENT = new APIClient(BACKEND_URL); diff --git a/src/utils/APIClient.js b/src/utils/APIClient.js new file mode 100644 index 0000000..551fc32 --- /dev/null +++ b/src/utils/APIClient.js @@ -0,0 +1,24 @@ +import axios from "axios"; + +export class APIClient { + #dbUrl = ""; + + constructor(dbUrl) { + if (typeof dbUrl !== "string") throw new Error("Database URL is not a string"); + this.#dbUrl = dbUrl; + } + async updateEvents() { + const rq = await axios.get(`${this.#dbUrl}/api/getEvents`); + if (rq.status !== 200) throw new Error(`Request failed with status code ${rq.status}: ${rq.statusText}`); + return rq.data; + } + async getEvent(id) { + if (typeof id !== "string") throw new TypeError("Invalid ID type"); + const events = await this.updateEvents(); + return events.find((e) => e.id == id) ?? null; + } + async createEvent(data) { + return; + // Not finished + } +}