import { backendFetch } from "./backend"; import { apiError, errorKind, isApiError, normalizeCollection, parseBody, type RawCollection, } from "./api"; import type { CollectionResult, DictionaryResult, Language } from "@/types/api"; async function serverRequest(path: string, init?: RequestInit): Promise { let response: Response; try { response = await backendFetch(path, init); } catch { throw apiError("network"); } if (!response.ok) throw apiError(errorKind(response.status)); return parseBody(response); } export async function getCollections(): Promise { try { const raw = await serverRequest("/api/collections"); return raw.map(normalizeCollection); } catch (err) { if (isApiError(err) && err.kind === "not-found") return []; throw err; } } export async function getCollection(id: string): Promise { const raw = await serverRequest(`/api/collections/${encodeURIComponent(id)}`); return normalizeCollection(raw); } export function lookupDictionary( lang: Language, word: string ): Promise { return serverRequest( `/api/dictionary/${lang}/${encodeURIComponent(word)}` ); }