File size: 845 Bytes
e91185c
bc832fa
 
d9e84cd
 
bc832fa
d9e84cd
bc832fa
e91185c
 
 
d9e84cd
bc832fa
e91185c
 
 
 
 
 
 
 
 
 
 
 
d9e84cd
 
e91185c
 
bc832fa
e91185c
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
const BASE_URL = 'http://localhost:8000';

export async function fetchApi<T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<T> {
  const headers = new Headers(options.headers || {});

  // Default to JSON content type for non-FormData requests
  if (!headers.has('Content-Type') && !(options.body instanceof FormData)) {
    headers.set('Content-Type', 'application/json');
  }

  const response = await fetch(`${BASE_URL}${endpoint}`, {
    ...options,
    headers,
  });

  if (!response.ok) {
    let errorMsg = 'An unexpected error occurred';
    try {
      const errorData = await response.json();
      errorMsg = errorData.detail || errorMsg;
    } catch { /* ignore parse error */ }
    throw new Error(errorMsg);
  }

  // Handle empty responses
  if (response.status === 204) return {} as T;

  return response.json();
}