import * as SecureStore from 'expo-secure-store'; const BACKEND_URL_KEY = 'backend_url'; const DEFAULT_URL = 'http://localhost:3001'; // Get stored or default backend URL export async function getBackendUrl(): Promise { try { const stored = await SecureStore.getItemAsync(BACKEND_URL_KEY); return stored || DEFAULT_URL; } catch { return DEFAULT_URL; } } // Set the backend URL export async function setBackendUrl(url: string): Promise { try { await SecureStore.setItemAsync(BACKEND_URL_KEY, url); } catch (e) { console.error('Failed to save backend URL:', e); } } // Clear stored backend URL (reset to default) export async function clearBackendUrl(): Promise { try { await SecureStore.deleteItemAsync(BACKEND_URL_KEY); } catch { // Ignore errors } } import { authClient } from './auth-client'; /** * Central API client for all network requests * Automatically attaches auth cookies to every request */ export async function apiFetch(endpoint: string, options: RequestInit = {}): Promise { const baseURL = await getBackendUrl(); const url = `${baseURL}${endpoint}`; // Get auth cookies const cookies = authClient.getCookie(); const headers: Record = { 'Content-Type': 'application/json', ...(typeof options.headers === 'object' ? (options.headers as Record) : {}), }; if (cookies) { headers.Cookie = cookies; } const response = await fetch(url, { ...options, headers, credentials: 'omit', }); 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: (endpoint: string) => apiFetch(endpoint, { method: 'GET' }), post: (endpoint: string, body?: unknown) => apiFetch(endpoint, { method: 'POST', body: body ? JSON.stringify(body) : undefined, }), put: (endpoint: string, body?: unknown) => apiFetch(endpoint, { method: 'PUT', body: body ? JSON.stringify(body) : undefined, }), delete: (endpoint: string) => apiFetch(endpoint, { method: 'DELETE' }), };