/ src / lib / util / sort-products.ts
sort-products.ts
 1  import { HttpTypes } from "@medusajs/types"
 2  import { SortOptions } from "@modules/store/components/refinement-list/sort-products"
 3  
 4  interface MinPricedProduct extends HttpTypes.StoreProduct {
 5    _minPrice?: number
 6  }
 7  
 8  /**
 9   * Helper function to sort products by price until the store API supports sorting by price
10   * @param products
11   * @param sortBy
12   * @returns products sorted by price
13   */
14  export function sortProducts(
15    products: HttpTypes.StoreProduct[],
16    sortBy: SortOptions
17  ): HttpTypes.StoreProduct[] {
18    let sortedProducts = products as MinPricedProduct[]
19  
20    if (["price_asc", "price_desc"].includes(sortBy)) {
21      // Precompute the minimum price for each product
22      sortedProducts.forEach((product) => {
23        if (product.variants && product.variants.length > 0) {
24          product._minPrice = Math.min(
25            ...product.variants.map(
26              (variant) => variant?.calculated_price?.calculated_amount || 0
27            )
28          )
29        } else {
30          product._minPrice = Infinity
31        }
32      })
33  
34      // Sort products based on the precomputed minimum prices
35      sortedProducts.sort((a, b) => {
36        const diff = a._minPrice! - b._minPrice!
37        return sortBy === "price_asc" ? diff : -diff
38      })
39    }
40  
41    if (sortBy === "created_at") {
42      sortedProducts.sort((a, b) => {
43        return (
44          new Date(b.created_at!).getTime() - new Date(a.created_at!).getTime()
45        )
46      })
47    }
48  
49    return sortedProducts
50  }