Files
DataClaw/frontend/src/lib/api.ts
T
2026-03-16 17:26:02 +08:00

64 lines
2.2 KiB
TypeScript

const API_BASE_URL = ''; // Relative path because of proxy
interface RequestOptions extends RequestInit {
headers?: Record<string, string>;
}
async function request<T>(url: string, options: RequestOptions = {}): Promise<T> {
const token = localStorage.getItem('token');
const defaultHeaders: Record<string, string> = {
...(token ? { 'Authorization': `Bearer ${token}` } : {}),
};
// Only set Content-Type to application/json if data is not FormData
if (!(options.body instanceof FormData)) {
defaultHeaders['Content-Type'] = 'application/json';
}
const config: RequestInit = {
...options,
headers: {
...defaultHeaders,
...options.headers,
},
};
try {
const response = await fetch(`${API_BASE_URL}${url}`, config);
if (!response.ok) {
if (response.status === 401) {
// Handle unauthorized (e.g., redirect to login or clear store)
localStorage.removeItem('token');
localStorage.removeItem('user');
// You might want to trigger a custom event or use window.location here
}
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.detail || errorData.message || `API Error: ${response.statusText}`);
}
// Handle empty responses (e.g. 204 No Content)
if (response.status === 204) {
return {} as T;
}
return await response.json();
} catch (error) {
console.error('API Request Failed:', error);
throw error;
}
}
export const api = {
get: <T>(url: string, options?: RequestOptions) => request<T>(url, { ...options, method: 'GET' }),
post: <T>(url: string, data: any, options?: RequestOptions) =>
request<T>(url, { ...options, method: 'POST', body: data instanceof FormData ? data : JSON.stringify(data) }),
put: <T>(url: string, data: any, options?: RequestOptions) =>
request<T>(url, { ...options, method: 'PUT', body: data instanceof FormData ? data : JSON.stringify(data) }),
delete: <T>(url: string, options?: RequestOptions) => request<T>(url, { ...options, method: 'DELETE' }),
patch: <T>(url: string, data: any, options?: RequestOptions) =>
request<T>(url, { ...options, method: 'PATCH', body: data instanceof FormData ? data : JSON.stringify(data) }),
};