1 import { MARKETS, type MarketCode } from "../config/markets"
2
3 export type CatalogProduct = {
4 id: string
5 title: string
6 handle: string
7 thumbnail: string | null
8 }
9
10 type ProductResponse = { products?: unknown }
11 type RegionResponse = { regions?: unknown }
12
13 export class CatalogError extends Error {
14 constructor(message: string, public readonly status?: number) {
15 super(message)
16 this.name = "CatalogError"
17 }
18 }
19
20 function parseProduct(value: unknown): CatalogProduct | null {
21 if (!value || typeof value !== "object") return null
22 const p = value as Record<string, unknown>
23 if (typeof p.id !== "string" || typeof p.title !== "string" || typeof p.handle !== "string") return null
24 return {
25 id: p.id,
26 title: p.title,
27 handle: p.handle,
28 thumbnail: typeof p.thumbnail === "string" && /^https?:\/\//.test(p.thumbnail) ? p.thumbnail : null,
29 }
30 }
31
32 /** Fetch public product summaries from Medusa Store API. Region pricing requires a resolved region_id. */
33 export async function fetchCatalog(
34 market: MarketCode,
35 options: { backendUrl: string; publishableKey: string; signal?: AbortSignal; fetcher?: typeof fetch },
36 ): Promise<CatalogProduct[]> {
37 const { backendUrl, publishableKey, signal, fetcher = fetch } = options
38 if (!/^https?:\/\//.test(backendUrl)) throw new CatalogError("A valid backend URL is required")
39 if (!publishableKey.trim()) throw new CatalogError("Medusa publishable key is required")
40 const headers = { "x-publishable-api-key": publishableKey, accept: "application/json" }
41 const regionsResponse = await fetcher(new URL("/store/regions", backendUrl).toString(), { signal, headers })
42 if (!regionsResponse.ok) throw new CatalogError("Medusa regions API request failed", regionsResponse.status)
43 const regionBody: RegionResponse = await regionsResponse.json()
44 if (!Array.isArray(regionBody.regions)) throw new CatalogError("Invalid Medusa regions response")
45 const countryCode = MARKETS[market].countryCode
46 const region = regionBody.regions.find((item: unknown) => {
47 if (!item || typeof item !== "object") return false
48 const candidate = item as { id?: unknown; countries?: unknown }
49 return typeof candidate.id === "string" && Array.isArray(candidate.countries) && candidate.countries.some((country: unknown) =>
50 country !== null && typeof country === "object" && (country as { iso_2?: unknown }).iso_2 === countryCode,
51 )
52 }) as { id: string } | undefined
53 if (!region) throw new CatalogError("Selected country is not configured in a Medusa region")
54 const url = new URL("/store/products", backendUrl)
55 url.searchParams.set("limit", "24")
56 url.searchParams.set("region_id", region.id)
57 const response = await fetcher(url.toString(), {
58 signal,
59 headers,
60 })
61 if (!response.ok) throw new CatalogError("Medusa product API request failed", response.status)
62 const body: ProductResponse = await response.json()
63 if (!Array.isArray(body.products)) throw new CatalogError("Invalid Medusa product API response")
64 return body.products.map(parseProduct).filter((p): p is CatalogProduct => p !== null)
65 }