diff options
Diffstat (limited to 'garden/src/api.ts')
| -rw-r--r-- | garden/src/api.ts | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/garden/src/api.ts b/garden/src/api.ts new file mode 100644 index 0000000..fc090a7 --- /dev/null +++ b/garden/src/api.ts @@ -0,0 +1,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 }; +}
\ No newline at end of file |
