summaryrefslogtreecommitdiff
path: root/garden/src/api.ts
blob: 53766a90ee5fc8e1d1e8c6fed559dadba611aa01 (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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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 text = await response.text();
  const data = text ? JSON.parse(text) : null;

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

export async function uploadFile<T>(path: string, file: File, token: string): Promise<APIResponse<T>> {
  const form = new FormData();
  form.append("file", file);

  const response = await fetch(`${API_URL}${path}`, {
    method: "POST",
    headers: { "Authorization": `Bearer ${token}` },
    body: form,
  });

  const text = await response.text();
  const data = text ? JSON.parse(text) : null;

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