48 lines · 1.3 KB
1 /**
2 * API client for the gitfastr Worker.
3 * In production, the Worker and Pages share the same domain or use a configured API URL.
4 * In dev, the Worker runs on a different port.
5 */
6
7 const API_BASE = import.meta.env.PUBLIC_API_URL || 'http://localhost:8321';
8
9 interface FetchOptions {
10 method?: string;
11 body?: any;
12 cookie?: string;
13 }
14
15 async function apiFetch(path: string, opts: FetchOptions = {}) {
16 const headers: Record<string, string> = {};
17
18 if (opts.body) {
19 headers['Content-Type'] = 'application/json';
20 }
21 if (opts.cookie) {
22 headers['Cookie'] = opts.cookie;
23 }
24
25 const response = await fetch(`${API_BASE}${path}`, {
26 method: opts.method || 'GET',
27 headers,
28 body: opts.body ? JSON.stringify(opts.body) : undefined,
29 });
30
31 if (!response.ok) {
32 const error = await response.json().catch(() => ({ error: response.statusText }));
33 throw new Error((error as any).error || `API error: ${response.status}`);
34 }
35
36 return response;
37 }
38
39 export async function apiGet(path: string, cookie?: string) {
40 const res = await apiFetch(path, { cookie });
41 return res.json();
42 }
43
44 export async function apiPost(path: string, body: any, cookie?: string) {
45 const res = await apiFetch(path, { method: 'POST', body, cookie });
46 return { data: await res.json(), headers: res.headers };
47 }
48