summaryrefslogtreecommitdiff
path: root/garden/src/api.ts
blob: fc090a74acba94414849491884948a234abcde0d (plain)
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
import { API_URL } from "./config";

interface APIOptions {
  method?: string;
  body?: unknown;
  token?: string | null;
}

interface APIResponse<T> {
  ok: boolean;
  status: number;
  data: T;
}

export async function api<T>(path: string, options: APIOptions = {}): Promise<APIResponse<T>> {
  const headers: Record<string, string> = {};

  if (options.body) {
    headers["Content-Type"] = "application/json";
  }

  if (options.token) {
    headers["Authorization"] = `Bearer ${options.token}`;
  }

  const response = await fetch(`${API_URL}${path}`, {
    method: options.method || "GET",
    headers,
    body: options.body ? JSON.stringify(options.body) : undefined,
  });

  const data = await response.json();

  return { ok: response.ok, status: response.status, data };
}