Implement basic saved point editor

This commit is contained in:
ThePetrovich 2025-07-02 15:32:46 +08:00
parent bb390d50dc
commit 0f79cefdac
12 changed files with 414 additions and 41 deletions

64
src/lib/api/base.ts Normal file
View file

@ -0,0 +1,64 @@
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) {
throw new Error(`HTTP error! status: ${response.status}`);
}
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);
throw 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",
});
}