From 024319f00d830017bbc41623e50aa5b118d757b1 Mon Sep 17 00:00:00 2001 From: dinesh Date: Tue, 26 May 2026 12:38:21 +0530 Subject: [PATCH] feat: add centralized authenticated API request handler for mobile --- apps/mobile/src/utils/apiClient.ts | 36 ++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 apps/mobile/src/utils/apiClient.ts diff --git a/apps/mobile/src/utils/apiClient.ts b/apps/mobile/src/utils/apiClient.ts new file mode 100644 index 0000000..a4b78f0 --- /dev/null +++ b/apps/mobile/src/utils/apiClient.ts @@ -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( + endpoint: string, + { method = 'GET', body, token, onUnauthorized }: RequestOptions +): Promise { + 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; +} \ No newline at end of file