Resolve Medusa region by country before fetching market-specific products
davoodmehraban89 committed
Oct 13, 2026 at 23:12 UTC
50e837c82e3bb6629328b8aa7486e6973142ac11
1 file changed
+17
-4
commerce/src/api/catalog.ts
+17
-4
@@ -8,6 +8,7 @@ export type CatalogProduct = {
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) {
@@ -36,17 +37,29 @@ export async function fetchCatalog(
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")
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.
56
+ url.searchParams.set("region_id", region.id)
57
const response = await fetcher(url.toString(), {
58
signal,
45
- headers: { "x-publishable-api-key": publishableKey, accept: "application/json" },
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")
50
- void MARKETS[market]
64
return body.products.map(parseProduct).filter((p): p is CatalogProduct => p !== null)
65
}