- App now prompts for backend URL on first launch - Stores in SecureStore for persistence - Default: http://localhost:3001 - Can be changed in app settings - Backend setup screen at /app/(auth)/backend-setup.tsx
84 lines
2.2 KiB
TypeScript
84 lines
2.2 KiB
TypeScript
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<string> {
|
|
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<void> {
|
|
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<void> {
|
|
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<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
|
|
const baseURL = await getBackendUrl();
|
|
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',
|
|
});
|
|
|
|
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' }),
|
|
};
|