regions.ts
1 "use server" 2 3 import { sdk } from "@lib/config" 4 import medusaError from "@lib/util/medusa-error" 5 import { HttpTypes } from "@medusajs/types" 6 import { getCacheOptions } from "./cookies" 7 8 export const listRegions = async () => { 9 const next = { 10 ...(await getCacheOptions("regions")), 11 } 12 13 return sdk.client 14 .fetch<{ regions: HttpTypes.StoreRegion[] }>(`/store/regions`, { 15 method: "GET", 16 next, 17 cache: "force-cache", 18 }) 19 .then(({ regions }) => regions) 20 .catch(medusaError) 21 } 22 23 export const retrieveRegion = async (id: string) => { 24 const next = { 25 ...(await getCacheOptions(["regions", id].join("-"))), 26 } 27 28 return sdk.client 29 .fetch<{ region: HttpTypes.StoreRegion }>(`/store/regions/${id}`, { 30 method: "GET", 31 next, 32 cache: "force-cache", 33 }) 34 .then(({ region }) => region) 35 .catch(medusaError) 36 } 37 38 const regionMap = new Map<string, HttpTypes.StoreRegion>() 39 40 export const getRegion = async (countryCode: string) => { 41 try { 42 if (regionMap.has(countryCode)) { 43 return regionMap.get(countryCode) 44 } 45 46 const regions = await listRegions() 47 48 if (!regions) { 49 return null 50 } 51 52 regions.forEach((region) => { 53 region.countries?.forEach((c) => { 54 regionMap.set(c?.iso_2 ?? "", region) 55 }) 56 }) 57 58 const region = countryCode 59 ? regionMap.get(countryCode) 60 : regionMap.get("us") 61 62 return region 63 } catch (e: any) { 64 return null 65 } 66 }