27 lines
786 B
TypeScript
27 lines
786 B
TypeScript
/**
|
|
* Client-side fetch function for API requests.
|
|
* A simple wrapper over fetch with improved error handling.
|
|
*/
|
|
export async function fetchData<T = any>(url: string, options: RequestInit = {}): Promise<T> {
|
|
try {
|
|
const res = await fetch(url, options);
|
|
|
|
// Check for no content response
|
|
if (res.status === 204) {
|
|
return {} as T;
|
|
}
|
|
|
|
// Handle errors
|
|
if (!res.ok) {
|
|
const errorData = await res.json().catch(() => ({}));
|
|
const errorMessage = errorData.message || errorData.error || `Request failed: ${res.status} ${res.statusText}`;
|
|
throw new Error(errorMessage);
|
|
}
|
|
|
|
// Parse normal response
|
|
return await res.json();
|
|
} catch (error) {
|
|
console.error(`Fetch error at ${url}:`, error);
|
|
throw error;
|
|
}
|
|
} |