import type { ApiError } from "@/typings"; type Body = undefined | FormData | Record; export class ApiClient { constructor(private baseUrl: string) {} private async request(method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE", path: string, body?: Body): Promise<{ data: T; error: null; } | { data: null; error: string; }> { const headers: Record = {}; if (body && !(body instanceof FormData)) { headers["Content-Type"] = "application/json"; } const response = await fetch(`${this.baseUrl}${path}`, { credentials: "include", method, body: !body || body instanceof FormData ? body : JSON.stringify(body), headers }) .catch(() => null); if (!response || !response.headers.get("Content-Type")?.toLowerCase()?.startsWith("application/json")) { return { data: null, error: response?.statusText || "Network error" }; } const data = await response.json() as T | ApiError; if (data && "message" in data) { return { data: null, error: data.message }; } return { data, error: null }; } get(path: string) { return this.request("GET", path); } post(path: string, body?: Body) { return this.request("POST", path, body); } patch(path: string, body?: Body) { return this.request("PATCH", path, body); } put(path: string, body?: Body) { return this.request("PUT", path, body); } delete(path: string) { return this.request("DELETE", path); } }