Skip to content

Commit 10f47b9

Browse files
authored
feat: add centralized authenticated API request handler for mobile (#338)
1 parent 6a1c6a2 commit 10f47b9

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

apps/mobile/src/utils/apiClient.ts

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { API_BASE_URL } from '../config';
2+
3+
type RequestOptions = {
4+
method?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
5+
body?: unknown;
6+
token: string | null;
7+
onUnauthorized?: () => void;
8+
};
9+
10+
export async function apiRequest<T>(
11+
endpoint: string,
12+
{ method = 'GET', body, token, onUnauthorized }: RequestOptions
13+
): Promise<T> {
14+
const headers: HeadersInit = {
15+
'Content-Type': 'application/json',
16+
...(token ? { Authorization: `Bearer ${token}` } : {}),
17+
};
18+
19+
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
20+
method,
21+
headers,
22+
...(body ? { body: JSON.stringify(body) } : {}),
23+
});
24+
25+
if (response.status === 401 || response.status === 403) {
26+
onUnauthorized?.();
27+
throw new Error('Unauthorized');
28+
}
29+
30+
if (!response.ok) {
31+
const error = await response.json().catch(() => ({}));
32+
throw new Error(error?.message ?? `Request failed: ${response.status}`);
33+
}
34+
35+
return response.json() as Promise<T>;
36+
}

0 commit comments

Comments
 (0)