Implement catalog API integration and tests: commerce/src/api/catalog.ts
davoodmehraban89 committed
Oct 13, 2026 at 23:12 UTC
16f9da8b1205c373c0cc6ab8cf8d885b46298525
1 file changed
+52
commerce/src/api/catalog.ts
new
+52
@@ -0,0 +1,52 @@
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
+
12
+export class CatalogError extends Error {
13
+ constructor(message: string, public readonly status?: number) {
14
+ super(message)
15
+ this.name = "CatalogError"
16
+ }
17
+}
18
+
19
+function parseProduct(value: unknown): CatalogProduct | null {
20
+ if (!value || typeof value !== "object") return null
21
+ const p = value as Record<string, unknown>
22
+ if (typeof p.id !== "string" || typeof p.title !== "string" || typeof p.handle !== "string") return null
23
+ return {
24
+ id: p.id,
25
+ title: p.title,
26
+ handle: p.handle,
27
+ thumbnail: typeof p.thumbnail === "string" && /^https?:\/\//.test(p.thumbnail) ? p.thumbnail : null,
28
+ }
29
+}
30
+
31
+/** Fetch public product summaries from Medusa Store API. Region pricing requires a resolved region_id. */
32
+export async function fetchCatalog(
33
+ market: MarketCode,
34
+ options: { backendUrl: string; publishableKey: string; signal?: AbortSignal; fetcher?: typeof fetch },
35
+): Promise<CatalogProduct[]> {
36
+ const { backendUrl, publishableKey, signal, fetcher = fetch } = options
37
+ if (!/^https?:\/\//.test(backendUrl)) throw new CatalogError("A valid backend URL is required")
38
+ if (!publishableKey.trim()) throw new CatalogError("Medusa publishable key is required")
39
+ const url = new URL("/store/products", backendUrl)
40
+ url.searchParams.set("limit", "24")
41
+ // Country selection alone must not be mistaken for Medusa region resolution.
42
+ // Region IDs and price context will be supplied by a dedicated region resolver.
43
+ const response = await fetcher(url.toString(), {
44
+ signal,
45
+ headers: { "x-publishable-api-key": publishableKey, accept: "application/json" },
46
+ })
47
+ if (!response.ok) throw new CatalogError("Medusa product API request failed", response.status)
48
+ const body: ProductResponse = await response.json()
49
+ if (!Array.isArray(body.products)) throw new CatalogError("Invalid Medusa product API response")
50
+ void MARKETS[market]
51
+ return body.products.map(parseProduct).filter((p): p is CatalogProduct => p !== null)
52
+}