// Adapted from legacy singleProduct.vue's own fetch (GET /product/:id). // // Reads ONE product from GET /catalog/products/:id. // // It used to fetch the shared catalogue and `find()` the row in it, because the // API had no single-product route. With the real catalogue reaching ~16k // products that meant opening any product could download all of them, so the // route now exists (plan step 2) and this is the first caller moved onto it. // // `initial` seeds the page with the ProductSummary the tapped card already // holds — the same shape, from the same endpoint — so the detail view renders // complete on its first frame instead of mounting blank and jumping when the // fetch lands. The read still runs, silently, and only replaces the product if // the server's copy actually differs (stock moved since the list loaded). // // The silent refresh waits until the opening morph (ProductMorph.vue, ≤420ms) // is over: swapping the product and re-rendering mid-animation drops frames. import { ref } from 'vue' import { api, UnauthorizedError, type ProductSummary } from '../api/client' const SEEDED_REFRESH_DELAY_MS = 600 /** A 404 from the API client, which throws `API failed (404): …`. */ function isNotFound(e: unknown): boolean { return e instanceof Error && !(e instanceof UnauthorizedError) && /\(404\)/.test(e.message) } export function useProductDetail(id: string, initial?: ProductSummary | null) { const loading = ref(false) const flag = ref(Boolean(initial)) const notFound = ref(false) const productRef = ref(initial ?? null) const load = async () => { const seeded = productRef.value !== null if (seeded) await new Promise((resolve) => setTimeout(resolve, SEEDED_REFRESH_DELAY_MS)) else loading.value = true try { const found = await api.getProduct(id) if (seeded) { if (JSON.stringify(found) !== JSON.stringify(productRef.value)) productRef.value = found } else { productRef.value = found } flag.value = true } catch (e) { // Only a real 404 means "no such product". Anything else — offline, a // 500 — must not render the "not found" page: before this route existed // a failed catalogue fetch left `notFound` false, and that is still the // right answer, because the product may well exist. if (isNotFound(e)) { if (!seeded) { productRef.value = null notFound.value = true } // Seeded and now 404: the product was pulled from the storefront while // the page was open. The card's copy stays on screen rather than // blanking under the person mid-read; the cart refuses it at checkout. } else { console.log(e) } flag.value = true } finally { loading.value = false } } return { loading, flag, notFound, productRef, load } }