Guest User

custom-products route.ts

a guest
Jan 2nd, 2025
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import type {
  2.   MedusaRequest,
  3.   MedusaResponse,
  4. } from "@medusajs/framework/http"
  5. import { StoreProduct } from "@medusajs/framework/types";
  6. import { ContainerRegistrationKeys, QueryContext } from "@medusajs/framework/utils"
  7.  
  8. type SortOptions = "price_asc" | "price_desc" | "created_at";
  9. interface MinPricedProduct extends StoreProduct {
  10.   _minPrice?: number
  11. }
  12.  
  13. /**
  14.  * Helper function to sort products by price until the store API supports sorting by price
  15.  * @param products
  16.  * @param sortBy
  17.  * @returns products sorted by price
  18.  */
  19. export function sortProducts(
  20.   products: StoreProduct[],
  21.   sortBy: SortOptions
  22. ): StoreProduct[] {
  23.   let sortedProducts = products as MinPricedProduct[]
  24.  
  25.   if (["price_asc", "price_desc"].includes(sortBy)) {
  26.     // Precompute the minimum price for each product
  27.     sortedProducts.forEach((product) => {
  28.       if (product.variants && product.variants.length > 0) {
  29.         product._minPrice = Math.min(
  30.           ...product.variants.map(
  31.             (variant) => variant?.calculated_price?.calculated_amount || 0
  32.           )
  33.         )
  34.       } else {
  35.         product._minPrice = Infinity
  36.       }
  37.     })
  38.  
  39.     // Sort products based on the precomputed minimum prices
  40.     sortedProducts.sort((a, b) => {
  41.       const diff = a._minPrice! - b._minPrice!
  42.       return sortBy === "price_asc" ? diff : -diff
  43.     })
  44.   }
  45.  
  46.   if (sortBy === "created_at") {
  47.     sortedProducts.sort((a, b) => {
  48.       return (
  49.         new Date(b.created_at!).getTime() - new Date(a.created_at!).getTime()
  50.       )
  51.     })
  52.   }
  53.  
  54.   return sortedProducts
  55. }
  56.  
  57. export const GET = async (
  58.   req: MedusaRequest,
  59.   res: MedusaResponse
  60. ) => {
  61.   const query = req.scope.resolve(ContainerRegistrationKeys.QUERY);
  62.   const customFieldIds = req.query.customFieldIds != null && req.query.customFieldIds != '' ?
  63.     (req.query.customFieldIds as string).split(',')
  64.     : [];
  65.   const currency_code = req.query.currency_code as string ?? 'sek';
  66.   const country_code = req.query.country_code as string ?? 'se';
  67.   const limit = req.query.limit as string ?? '12';
  68.   const skip = req.query.skip as string ?? '0';
  69.   const sortBy = req.query.sortBy as string ?? 'created_at';
  70.  
  71.   let { data: products } = await query.graph({
  72.     entity: "product",
  73.     fields: [
  74.       "*",
  75.       "variants.*",
  76.       "variants.calculated_price.*",
  77.       "custom_fields.value",
  78.     ],
  79.     context: {
  80.       variants: {
  81.         calculated_price: QueryContext({
  82.           currency_code,
  83.           country_code,
  84.         }),
  85.       },
  86.     },
  87.   });
  88.  
  89.   if (customFieldIds.length > 0) {
  90.     products = products.filter((product) => {
  91.       return product.custom_fields.filter((cf) => {
  92.         const value = JSON.stringify(cf.value);
  93.         return customFieldIds.find((id) => value.includes(id)) != null;
  94.       }).length > 0;
  95.     });
  96.   }
  97.  
  98.   products = products.slice(parseInt(skip), parseInt(skip) + parseInt(limit));
  99.  
  100.   const sortedProducts = sortProducts((products as unknown as StoreProduct[]), sortBy as SortOptions);
  101.  
  102.   res.json({
  103.     products: sortedProducts,
  104.     count: products.length,
  105.   });
  106. };
  107.  
Advertisement
Add Comment
Please, Sign In to add comment