File size: 981 Bytes
3193174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
34
35
36
37
const BASE_URL = "/api";

async function request<T>(
  method: string,
  endpoint: string,
  data?: unknown,
): Promise<T> {
  const options: RequestInit = {
    method,
    headers: { "Content-Type": "application/json" },
  };

  if (data !== undefined) {
    options.body = JSON.stringify(data);
  }

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

  if (!response.ok) {
    const text = await response.text().catch(() => response.statusText);
    throw new Error(text || `${method} ${endpoint} failed (${response.status})`);
  }

  if (response.status === 204) {
    return undefined as T;
  }

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

export const api = {
  get: <T>(endpoint: string) => request<T>("GET", endpoint),
  post: <T>(endpoint: string, data?: unknown) => request<T>("POST", endpoint, data),
  put: <T>(endpoint: string, data?: unknown) => request<T>("PUT", endpoint, data),
  delete: (endpoint: string) => request<void>("DELETE", endpoint),
};