35 lines
1009 B
TypeScript
35 lines
1009 B
TypeScript
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[];
|
|
}
|