Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions apps/mobile/src/utils/apiClient.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { API_BASE_URL } from '../config';

type RequestOptions = {
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
body?: unknown;
token: string | null;
onUnauthorized?: () => void;
};

export async function apiRequest<T>(
endpoint: string,
{ method = 'GET', body, token, onUnauthorized }: RequestOptions
): Promise<T> {
const headers: HeadersInit = {
'Content-Type': 'application/json',
...(token ? { Authorization: `Bearer ${token}` } : {}),
};

const response = await fetch(`${API_BASE_URL}${endpoint}`, {
method,
headers,
...(body ? { body: JSON.stringify(body) } : {}),
});

if (response.status === 401 || response.status === 403) {
onUnauthorized?.();
throw new Error('Unauthorized');
}

if (!response.ok) {
const error = await response.json().catch(() => ({}));
throw new Error(error?.message ?? `Request failed: ${response.status}`);
}

return response.json() as Promise<T>;
}