1
0
Fork 0
BitHarbor/frontend/src/api/base.ts
2026-04-07 23:21:40 +02:00

41 lines
1.3 KiB
TypeScript

export const getApiBaseUrl = () => import.meta.env.VITE_API_BASE_URL ?? 'http://localhost';
const getCookie = (name: string): string | null => {
const match = document.cookie.match(new RegExp(`(^|; )${name}=([^;]*)`));
const value = match?.[2];
return value ? decodeURIComponent(value) : null;
};
type ApiCallOptions = {
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
body?: unknown;
withCsrf?: boolean;
headers?: HeadersInit;
};
export const apiCall = async (path: string, options: ApiCallOptions = {}): Promise<Response> => {
const url = new URL(path, getApiBaseUrl());
const csrfToken = options.withCsrf ? getCookie('XSRF-TOKEN') : null;
const hasBody = options.body !== undefined;
return await fetch(url.toString(), {
method: options.method ?? 'GET',
credentials: 'include',
headers: {
Accept: 'application/json',
...(hasBody ? { 'Content-Type': 'application/json' } : {}),
...(csrfToken ? { 'X-XSRF-TOKEN': csrfToken } : {}),
...options.headers,
},
...(hasBody ? { body: JSON.stringify(options.body) } : {}),
});
};
export const csrf = async () => {
const response = await apiCall('/sanctum/csrf-cookie');
if (!response.ok) {
throw new Error(`Failed to get CSRF cookie (${response.status})`);
}
};