85 lines
2.8 KiB
TypeScript
85 lines
2.8 KiB
TypeScript
import { getCsrfToken } from "$lib/auth";
|
|
|
|
export const API_BASE_URL = "http://localhost:8000/api";
|
|
|
|
export async function fetchAPI<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
|
|
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<T>(endpoint: string, data: any): Promise<T> {
|
|
return fetchAPI<T>(endpoint, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify(data),
|
|
});
|
|
}
|
|
|
|
export function getAPI<T>(endpoint: string): Promise<T> {
|
|
return fetchAPI<T>(endpoint, {
|
|
method: "GET",
|
|
});
|
|
}
|
|
|
|
export function putAPI<T>(endpoint: string, data: any): Promise<T> {
|
|
return fetchAPI<T>(endpoint, {
|
|
method: "PUT",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify(data),
|
|
});
|
|
}
|
|
|
|
export function deleteAPI<T>(endpoint: string): Promise<T> {
|
|
return fetchAPI<T>(endpoint, {
|
|
method: "DELETE",
|
|
});
|
|
}
|