55 lines
1.9 KiB
TypeScript
55 lines
1.9 KiB
TypeScript
import { cache } from 'react';
|
|
|
|
import { listProductTypes, listProducts } from "@lib/data/products";
|
|
import { listRegions } from '@lib/data/regions';
|
|
import { getAnalysisElementMedusaProductIds } from '@/utils/medusa-product';
|
|
import type { StoreProduct } from '@medusajs/types';
|
|
|
|
async function countryCodesLoader() {
|
|
const countryCodes = await listRegions().then((regions) =>
|
|
regions?.map((r) => r.countries?.map((c) => c.iso_2)).flat(),
|
|
);
|
|
return countryCodes ?? [];
|
|
}
|
|
export const loadCountryCodes = cache(countryCodesLoader);
|
|
|
|
async function productTypesLoader() {
|
|
const { productTypes } = await listProductTypes();
|
|
return productTypes ?? [];
|
|
}
|
|
export const loadProductTypes = cache(productTypesLoader);
|
|
|
|
async function analysisPackagesLoader() {
|
|
const [countryCodes, productTypes] = await Promise.all([loadCountryCodes(), loadProductTypes()]);
|
|
const countryCode = countryCodes[0]!;
|
|
|
|
let analysisPackages: StoreProduct[] = [];
|
|
let analysisPackageElements: StoreProduct[] = [];
|
|
|
|
const productType = productTypes.find(({ metadata }) => metadata?.handle === 'analysis-packages');
|
|
if (!productType) {
|
|
return { analysisPackageElements, analysisPackages, countryCode };
|
|
}
|
|
|
|
const analysisPackagesResponse = await listProducts({
|
|
countryCode,
|
|
queryParams: { limit: 100, "type_id[0]": productType.id },
|
|
});
|
|
analysisPackages = analysisPackagesResponse.response.products;
|
|
|
|
const analysisElementMedusaProductIds = getAnalysisElementMedusaProductIds(analysisPackages);
|
|
if (analysisElementMedusaProductIds.length > 0) {
|
|
const { response: { products } } = await listProducts({
|
|
countryCode,
|
|
queryParams: {
|
|
id: analysisElementMedusaProductIds,
|
|
limit: 100,
|
|
},
|
|
});
|
|
analysisPackageElements = products;
|
|
}
|
|
|
|
return { analysisPackageElements, analysisPackages, countryCode };
|
|
}
|
|
export const loadAnalysisPackages = cache(analysisPackagesLoader);
|