From 3297c500a42e01b3698b4890f6da604e578b6d7d Mon Sep 17 00:00:00 2001 From: yiekheng Date: Sat, 2 May 2026 20:50:45 +0800 Subject: [PATCH] feat(web): add server-side api-server fetch helper --- web/lib/api.ts | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 web/lib/api.ts diff --git a/web/lib/api.ts b/web/lib/api.ts new file mode 100644 index 0000000..8a97313 --- /dev/null +++ b/web/lib/api.ts @@ -0,0 +1,34 @@ +import type { Acc, User } from "./types"; + +const API_BASE_URL = process.env.API_BASE_URL ?? "http://api-server:3000"; + +type FetchInit = { + method?: "GET" | "POST"; + body?: unknown; + cache?: RequestCache; +}; + +export async function fetchApi(path: string, options: FetchInit = {}): Promise { + const url = `${API_BASE_URL}${path}`; + const init: RequestInit = { + method: options.method ?? "GET", + cache: options.cache ?? "no-store", + headers: options.body ? { "content-type": "application/json" } : undefined, + body: options.body ? JSON.stringify(options.body) : undefined, + }; + const res = await fetch(url, init); + if (!res.ok) { + throw new Error(`API ${options.method ?? "GET"} ${path} failed: ${res.status}`); + } + return res.json(); +} + +export async function getAccounts(): Promise { + const data = await fetchApi("/acc/"); + return data as Acc[]; +} + +export async function getUsers(): Promise { + const data = await fetchApi("/user/"); + return data as User[]; +}