bagsy/apps/mobile/lib/api.ts

51 lines
1.5 KiB
TypeScript

import { authClient } from './auth-client';
/**
* Central API client for all network requests
* Automatically attaches auth cookies to every request
*/
export async function apiFetch<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
const baseURL = process.env.EXPO_PUBLIC_API_URL || 'http://localhost:3001';
const url = `${baseURL}${endpoint}`;
// Get auth cookies
const cookies = authClient.getCookie();
const headers: Record<string, string> = {
'Content-Type': 'application/json',
...(typeof options.headers === 'object' ? (options.headers as Record<string, string>) : {}),
};
if (cookies) {
headers.Cookie = cookies;
}
const response = await fetch(url, {
...options,
headers,
credentials: 'omit', // Prevent conflicts with manually set Cookie header
});
if (!response.ok) {
const error = await response.json().catch(() => ({ message: 'Unknown error' }));
throw new Error(error.message || `API error: ${response.status}`);
}
return response.json();
}
// Convenience methods
export const api = {
get: <T>(endpoint: string) => apiFetch<T>(endpoint, { method: 'GET' }),
post: <T>(endpoint: string, body?: unknown) =>
apiFetch<T>(endpoint, {
method: 'POST',
body: body ? JSON.stringify(body) : undefined,
}),
put: <T>(endpoint: string, body?: unknown) =>
apiFetch<T>(endpoint, {
method: 'PUT',
body: body ? JSON.stringify(body) : undefined,
}),
delete: <T>(endpoint: string) => apiFetch<T>(endpoint, { method: 'DELETE' }),
};