import { getCsrfToken } from "$lib/auth"; export const API_BASE_URL = "http://localhost:8000/api"; export async function fetchAPI(endpoint: string, options: RequestInit = {}): Promise { let csrfToken = await getCsrfToken(); if (!csrfToken) { console.warn("CSRF token not found, using empty string."); csrfToken = ""; } const url = `${API_BASE_URL}${endpoint}`; options.credentials = "include"; // Include cookies in the request options.headers = { ...options.headers, "Content-Type": "application/json", "X-CSRFToken": csrfToken, }; try { const response = await fetch(url, options); if (!response.ok) { let errorText = await response.json(); if ( errorText && typeof errorText === "object" && ("detail" in errorText || "field_errors" in errorText || "non_field_errors" in errorText) ) { // Handle structured error responses if ("detail" in errorText) { errorText = errorText.detail; } else if ("field_errors" in errorText) { errorText = Object.values(errorText.field_errors).join(", "); } else if ("non_field_errors" in errorText) { errorText = errorText.non_field_errors.join(", "); } } else { errorText = `Unexpected error: ${response.statusText}`; } throw new Error(`${errorText}`); } if (response.status === 204) { // No content response return {} as T; // Return an empty object for 204 responses } return (await response.json()) as T; } catch (error) { console.error(`Error fetching ${url}:`, error); if (error instanceof Error) { // If the error is an instance of Error, rethrow it return Promise.reject(new Error(`${error.message}`)); } return Promise.reject(new Error(`${error}`)); } } export function postAPI(endpoint: string, data: any): Promise { return fetchAPI(endpoint, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }); } export function getAPI(endpoint: string): Promise { return fetchAPI(endpoint, { method: "GET", }); } export function putAPI(endpoint: string, data: any): Promise { return fetchAPI(endpoint, { method: "PUT", headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }); } export function deleteAPI(endpoint: string): Promise { return fetchAPI(endpoint, { method: "DELETE", }); }