Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import type {
- MedusaRequest,
- MedusaResponse,
- } from "@medusajs/framework/http"
- import { StoreProduct } from "@medusajs/framework/types";
- import { ContainerRegistrationKeys, QueryContext } from "@medusajs/framework/utils"
- type SortOptions = "price_asc" | "price_desc" | "created_at";
- interface MinPricedProduct extends StoreProduct {
- _minPrice?: number
- }
- /**
- * Helper function to sort products by price until the store API supports sorting by price
- * @param products
- * @param sortBy
- * @returns products sorted by price
- */
- export function sortProducts(
- products: StoreProduct[],
- sortBy: SortOptions
- ): StoreProduct[] {
- let sortedProducts = products as MinPricedProduct[]
- if (["price_asc", "price_desc"].includes(sortBy)) {
- // Precompute the minimum price for each product
- sortedProducts.forEach((product) => {
- if (product.variants && product.variants.length > 0) {
- product._minPrice = Math.min(
- ...product.variants.map(
- (variant) => variant?.calculated_price?.calculated_amount || 0
- )
- )
- } else {
- product._minPrice = Infinity
- }
- })
- // Sort products based on the precomputed minimum prices
- sortedProducts.sort((a, b) => {
- const diff = a._minPrice! - b._minPrice!
- return sortBy === "price_asc" ? diff : -diff
- })
- }
- if (sortBy === "created_at") {
- sortedProducts.sort((a, b) => {
- return (
- new Date(b.created_at!).getTime() - new Date(a.created_at!).getTime()
- )
- })
- }
- return sortedProducts
- }
- export const GET = async (
- req: MedusaRequest,
- res: MedusaResponse
- ) => {
- const query = req.scope.resolve(ContainerRegistrationKeys.QUERY);
- const customFieldIds = req.query.customFieldIds != null && req.query.customFieldIds != '' ?
- (req.query.customFieldIds as string).split(',')
- : [];
- const currency_code = req.query.currency_code as string ?? 'sek';
- const country_code = req.query.country_code as string ?? 'se';
- const limit = req.query.limit as string ?? '12';
- const skip = req.query.skip as string ?? '0';
- const sortBy = req.query.sortBy as string ?? 'created_at';
- let { data: products } = await query.graph({
- entity: "product",
- fields: [
- "*",
- "variants.*",
- "variants.calculated_price.*",
- "custom_fields.value",
- ],
- context: {
- variants: {
- calculated_price: QueryContext({
- currency_code,
- country_code,
- }),
- },
- },
- });
- if (customFieldIds.length > 0) {
- products = products.filter((product) => {
- return product.custom_fields.filter((cf) => {
- const value = JSON.stringify(cf.value);
- return customFieldIds.find((id) => value.includes(id)) != null;
- }).length > 0;
- });
- }
- products = products.slice(parseInt(skip), parseInt(skip) + parseInt(limit));
- const sortedProducts = sortProducts((products as unknown as StoreProduct[]), sortBy as SortOptions);
- res.json({
- products: sortedProducts,
- count: products.length,
- });
- };
Advertisement
Add Comment
Please, Sign In to add comment