project-standalo-todo-super/app/lib/api.ts

46 lines
1.1 KiB
TypeScript

/**
* API client utilities for making authenticated requests
*/
export async function fetchWithAuth(url: string, options: RequestInit = {}) {
const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
const headers = new Headers(options.headers);
if (token) {
headers.set('Authorization', `Bearer ${token}`);
}
if (!headers.has('Content-Type') && options.body) {
headers.set('Content-Type', 'application/json');
}
return fetch(url, {
...options,
headers,
});
}
export async function apiGet<T>(url: string): Promise<T> {
const response = await fetchWithAuth(url);
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Request failed');
}
return data;
}
export async function apiPost<T>(url: string, body?: unknown): Promise<T> {
const response = await fetchWithAuth(url, {
method: 'POST',
body: body ? JSON.stringify(body) : undefined,
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Request failed');
}
return data;
}