let instance; const baseUrl = import.meta.env?.VITE_API_BASE_URL ?? "http://localhost:8080/api/v1"; class HttpClient { baseURL: string; commonHeaders: Headers; constructor(baseURL: string) { this.baseURL = baseURL; this.commonHeaders = new Headers({ "Content-Type": "application/json" }) if (instance) { throw new Error("New instance cannot be created!"); } instance = this; } private getURL(endpoint: string): URL { return new URL(endpoint, this.baseURL); } private token(): string | null { return localStorage.getItem('token'); } private async makeRequest(request: Request): Promise { return fetch(request) } async get({ endpoint, headers }: IHttpParameters): Promise { const url: URL = this.getURL(endpoint); headers = Object.assign(headers, this.commonHeaders); const request: Request = new Request(url, { method: "GET", headers }); return this.makeRequest(request); } async post({ endpoint, authenticated, body, headers }: IHttpParameters): Promise { const url = this.getURL(endpoint); if (authenticated) { const token: string | null = this.token(); headers.append('Authorization', `Bearer ${token}`); } const request: Request = new Request(url, { method: "POST", body: JSON.stringify(body), headers }) return this.makeRequest(request); } async patch({ endpoint, authenticated, headers }: IHttpParameters): Promise { const url = this.getURL(endpoint); if (authenticated) { } const response: Response = await fetch(url, { method: "PATCH", headers }); } async delete({ endpoint, authenticated, headers }: IHttpParameters): Promise { const url = this.getURL(endpoint); if (authenticated) { } const response: Response = await fetch(url, { method: "DELETE", headers }) } } interface IHttpParameters { endpoint: string; body: Record; authenticated: boolean; headers: Headers; } let http: Readonly = Object.freeze(new HttpClient(baseUrl)); export default http;