feat(web): add server-side api-server fetch helper
This commit is contained in:
parent
aa76131b23
commit
3297c500a4
34
web/lib/api.ts
Normal file
34
web/lib/api.ts
Normal file
@ -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<unknown> {
|
||||||
|
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<Acc[]> {
|
||||||
|
const data = await fetchApi("/acc/");
|
||||||
|
return data as Acc[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUsers(): Promise<User[]> {
|
||||||
|
const data = await fetchApi("/user/");
|
||||||
|
return data as User[];
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user