import type { Acc, User } from "./types"; const API_BASE_URL = process.env.API_BASE_URL ?? "http://api-server:3000"; // How long the Next.js data cache holds an /acc/ or /user/ response // before considering it stale. Tab switches and auto-refreshes within // this window are served from memory — no api-server / MySQL round-trip. // Mutations (update/create/delete) call revalidateTag() so the next // request always sees fresh data after a write. const CACHE_REVALIDATE_SECONDS = 30; export const ACCOUNTS_TAG = "accounts"; export const USERS_TAG = "users"; type FetchInit = { method?: "GET" | "POST"; body?: unknown; cache?: RequestCache; next?: { revalidate?: number; tags?: string[] }; }; export async function fetchApi(path: string, options: FetchInit = {}): Promise { const url = `${API_BASE_URL}${path}`; const init: RequestInit & { next?: FetchInit["next"] } = { method: options.method ?? "GET", headers: options.body ? { "content-type": "application/json" } : undefined, body: options.body ? JSON.stringify(options.body) : undefined, }; if (options.next) { init.next = options.next; } else { init.cache = options.cache ?? "no-store"; } 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/", { next: { revalidate: CACHE_REVALIDATE_SECONDS, tags: [ACCOUNTS_TAG] }, }); return data as Acc[]; } export async function getUsers(): Promise { const data = await fetchApi("/user/", { next: { revalidate: CACHE_REVALIDATE_SECONDS, tags: [USERS_TAG] }, }); return data as User[]; }