diff --git a/.changeset/many-experts-provide.md b/.changeset/many-experts-provide.md new file mode 100644 index 0000000000..236c2d337f --- /dev/null +++ b/.changeset/many-experts-provide.md @@ -0,0 +1,5 @@ +--- +"@medusajs/medusa": patch +--- + +chore(): Improve product list when there is a single sales channel diff --git a/packages/medusa/src/api/store/products/middlewares.ts b/packages/medusa/src/api/store/products/middlewares.ts index a7d15f1530..1a2f6d3d0e 100644 --- a/packages/medusa/src/api/store/products/middlewares.ts +++ b/packages/medusa/src/api/store/products/middlewares.ts @@ -5,9 +5,13 @@ import { authenticate, clearFiltersByKey, maybeApplyLinkFilter, + MedusaNextFunction, + MedusaRequest, + MedusaResponse, MiddlewareRoute, } from "@medusajs/framework/http" import { + ContainerRegistrationKeys, FeatureFlag, isPresent, ProductStatus, @@ -22,6 +26,42 @@ import { import * as QueryConfig from "./query-config" import { StoreGetProductsParams } from "./validators" +async function applyMaybeLinkFilterIfNecessary( + req: MedusaRequest, + res: MedusaResponse, + next: MedusaNextFunction +) { + const canUseIndex = !( + isPresent(req.filterableFields.tags) || + isPresent(req.filterableFields.categories) + ) + if (FeatureFlag.isFeatureEnabled(IndexEngineFeatureFlag.key) && canUseIndex) { + return next() + } + + const query = req.scope.resolve(ContainerRegistrationKeys.QUERY) + const salesChannelsQueryRes = await query.graph({ + entity: "sales_channels", + fields: ["id"], + pagination: { + skip: 0, + take: 1, + }, + }) + + const salesChannelCount = salesChannelsQueryRes.metadata?.count ?? 0 + if (!(salesChannelCount > 1)) { + delete req.filterableFields.sales_channel_id + return next() + } + + return maybeApplyLinkFilter({ + entryPoint: "product_sales_channel", + resourceId: "product_id", + filterableField: "sales_channel_id", + })(req, res, next) +} + export const storeProductRoutesMiddlewares: MiddlewareRoute[] = [ { method: ["GET"], @@ -35,24 +75,7 @@ export const storeProductRoutesMiddlewares: MiddlewareRoute[] = [ QueryConfig.listProductQueryConfig ), filterByValidSalesChannels(), - (req, res, next) => { - const canUseIndex = !( - isPresent(req.filterableFields.tags) || - isPresent(req.filterableFields.categories) - ) - if ( - FeatureFlag.isFeatureEnabled(IndexEngineFeatureFlag.key) && - canUseIndex - ) { - return next() - } - - return maybeApplyLinkFilter({ - entryPoint: "product_sales_channel", - resourceId: "product_id", - filterableField: "sales_channel_id", - })(req, res, next) - }, + applyMaybeLinkFilterIfNecessary, applyDefaultFilters({ status: ProductStatus.PUBLISHED, // TODO: the type here seems off and the implementation does not take into account $and and $or possible filters. Might be worth re working (original type used here was StoreGetProductsParamsType)