Nye-TeeOff/frontend/src/app/publicFacilities.ts
2026-04-26 12:12:40 +02:00

47 lines
1.2 KiB
TypeScript

import { API_URL } from "@/config/constants";
const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
export async function fetchPublicFacilities<T>(
view: string,
_revalidateSeconds: number,
{
allowEmpty = false,
attempts = 3,
}: {
allowEmpty?: boolean;
attempts?: number;
} = {},
): Promise<T[]> {
let lastError: Error | null = null;
for (let attempt = 1; attempt <= attempts; attempt += 1) {
try {
const res = await fetch(`${API_URL}/facilities?view=${view}`, {
cache: "no-store",
});
if (!res.ok) {
throw new Error(`API returnerte status ${res.status}`);
}
const data = await res.json();
if (!Array.isArray(data)) {
throw new Error("API returnerte ikke en liste");
}
if (!allowEmpty && data.length === 0) {
throw new Error("API returnerte tom liste");
}
return data as T[];
} catch (error) {
lastError = error instanceof Error ? error : new Error("Ukjent feil ved henting av anlegg");
if (attempt < attempts) {
await delay(attempt * 250);
}
}
}
throw lastError ?? new Error("Kunne ikke hente anlegg");
}