import { listPacks } from "@/lib/apiaries/offline-pack"; import type { StoredPack } from "./db"; import { isNetworkError } from "@/lib/http/fetch-with-timeout"; /** * The server's answer - or, only when the network failed, what the user's * offline packs say. A server refusal (ApiError: 403, 404, 400 ...) is never * covered up with pack data: the server knows better than an old pack. * When the packs have nothing (`fromPacks` returns null) or cannot be read, * the network error is passed on, so the caller shows "not loaded". * * Queries built on this read local storage when offline: give them * `networkMode: "always"`, or a paused retry would hide the fallback. */ export async function withPackFallback( fetcher: () => Promise, fromPacks: (packs: StoredPack[]) => T | null, ownerUserId: string, ): Promise { try { return await fetcher(); } catch (error) { if (!isNetworkError(error)) { throw error; } const fallback = await listPacks(ownerUserId).then(fromPacks, () => null); if (fallback === null) { throw error; } return fallback; } }