Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

feat(products): serve product lists through the Medusa index engine (#1740)

Viktor Holik88c37ec0f514
diff --git a/claude-progress.md b/claude-progress.md
index 72c98c5b7..934920222 100644
--- a/claude-progress.md
+++ b/claude-progress.md
@@ -14,6 +14,44 @@ session detail aggressively. The per-spec source of truth lives in
`bun run test:integration:http -- <pattern>`
- **Current blocker**: none
+## Session — Product lists on the Medusa index engine (2026-11-03), branch `feat/index-engine-product-lists`
+
+`GET /admin|/vendor|/store/products` now go through `api/utils/list-products.ts` `listProducts()`. It uses
+`query.index` when every filter key and the sort fall in the indexed whitelist, otherwise `query.graph` (categories,
+tags, variant options, withDeleted, admin `seller_id`). `count` = `estimate_count`, exact when the page isn't full;
+`estimate_count` is also returned. `withMercur` enables `index_engine` and injects `@medusajs/index` (direct dep
+of apps/api, integration-tests, templates/basic api). `product_seller` link is `filterable`. Vendor list no longer
+scans every seller's `product_seller` rows: visibility is own PRODUCT_ADD ids (draft/proposed), plus published with
+no `product_seller` row, plus published `id IN` this seller's own rows. It's passed per engine through
+`ProductVisibility`. The detail guard is one product query + the scoped authorship lookup. `has_offer` filters by
+`offer.product_id`. New index `IDX_product_change_created_by`. Tests: vendor `product.spec` 17/17 (new graph-fallback
+and count cases), admin `product` + `product-publish-and-sku` 26 pass (4 pre-existing skips), store `product/` 18/18,
+with deterministic index waits (`helpers/wait-for-indexed-products.ts`). Core tsc green; full `bun run build` not run.
+
+Open risk: sellers created after boot never land in the index (`seller.seller.created` doesn't reach it), so
+`sellers.id` filters are unusable. Production needs the Redis event bus for incremental index sync.
+
+Follow-up (same day, same PR #1740): Medusa Caching Module. `withMercur` sets the `caching` flag and registers
+`@medusajs/medusa/caching`, using the Redis provider when `projectConfig.redisUrl` is set (dep in apps/api +
+template) and in-memory otherwise (tests). `listProducts` takes `cache: { ttl, tags }`, always tags
+`Product:list:*` (automatic tags come from rows, so empty pages would otherwise never clear) and caps index-backed
+entries at 5s: one event clears the cache and starts the async index sync, so a request in between re-caches the
+pre-write state. Store 300s / admin 60s / vendor 60s + `LinkProductSeller:list:*` (link attach only clears that
+tag). Invalidation tests: store 22/22, vendor 19/19, admin 26 pass.
+
+Follow-ups (same day, same PR):
+- **Exact counts** on admin/vendor via an ids-only index call; it's what `query.index` sends internally, minus
+ pagination. Measured cost: 234ms vendor / 33ms admin at 20k.
+- **Routing:** plain lists go to `query.graph`; the index is only used for `product_seller` / sales channel / price
+ filters.
+- **Seller events:** the service overrides now use `@InjectManager` + `@EmitEvents` + `@MedusaContext`, so
+ `seller.seller.*` is emitted and sellers reach the index. Deployments need one full index sync.
+- **Previously no-op cache calls**, now live:
+ - CI caught them (store-offers, offer-region-prices). Each got the link/list tag that actually clears.
+ - Membership checks are no longer cached.
+- **Open:** tie ordering. `query.index` takes one sort key only, so there's no `id` tiebreak and paging can repeat or
+ skip products when `created_at` ties (on main too).
+
## Session — Extendable offer tables, grid and form fields (2026-10-26), branch `feat/extendable-offer-tables-forms`
Panel extensions can now hide, replace, and add columns and fields beyond list pages, reusing the existing
diff --git a/integration-tests/helpers/eventually.ts b/integration-tests/helpers/eventually.ts
new file mode 100644
index 000000000..e4edd9d68
--- /dev/null
+++ b/integration-tests/helpers/eventually.ts
@@ -0,0 +1,16 @@
+export const eventually = async <T>(
+ assertion: () => Promise<T>,
+ { timeout = 10000, interval = 200 }: { timeout?: number; interval?: number } = {}
+): Promise<T> => {
+ const deadline = Date.now() + timeout
+ while (true) {
+ try {
+ return await assertion()
+ } catch (e) {
+ if (Date.now() > deadline) {
+ throw e
+ }
+ await new Promise((resolve) => setTimeout(resolve, interval))
+ }
+ }
+}
diff --git a/integration-tests/helpers/wait-for-indexed-products.ts b/integration-tests/helpers/wait-for-indexed-products.ts
new file mode 100644
index 000000000..9197330c7
--- /dev/null
+++ b/integration-tests/helpers/wait-for-indexed-products.ts
@@ -0,0 +1,44 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+
+import { eventually } from "./eventually"
+
+/**
+ * The index syncs asynchronously after writes. Matches through index filters
+ * only: response fields are hydrated from the database and would report a
+ * state the index does not have yet.
+ */
+export const waitForIndexedProducts = async (
+ container: MedusaContainer,
+ expected: {
+ id: string
+ status?: string
+ title?: string
+ restricted: boolean
+ }[]
+) => {
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+
+ await eventually(
+ async () => {
+ for (const entry of expected) {
+ const { data } = await query.index({
+ entity: "product",
+ fields: ["id"],
+ filters: {
+ id: entry.id,
+ ...(entry.status ? { status: entry.status } : {}),
+ ...(entry.title ? { title: entry.title } : {}),
+ product_seller: {
+ id: entry.restricted ? { $ne: null } : { $eq: null },
+ },
+ },
+ })
+ if (data.length !== 1) {
+ throw new Error(`Product ${entry.id} is not indexed yet`)
+ }
+ }
+ },
+ { timeout: 15000, interval: 100 }
+ )
+}
diff --git a/integration-tests/http/product/store/offer-product-price.spec.ts b/integration-tests/http/product/store/offer-product-price.spec.ts
index 4776f732c..cb4dd26ed 100644
--- a/integration-tests/http/product/store/offer-product-price.spec.ts
+++ b/integration-tests/http/product/store/offer-product-price.spec.ts
@@ -19,6 +19,7 @@ import {
generatePublishableKey,
generateStoreHeaders,
} from "../../../helpers/create-admin-user"
+import { waitForIndexedProducts } from "../../../helpers/wait-for-indexed-products"
const approveSeller = async (container: MedusaContainer, sellerId: string) => {
const sellerModule: any = container.resolve(MercurModules.SELLER)
@@ -93,6 +94,9 @@ medusaIntegrationTestRunner({
result.seller.id as string,
[productId]
)
+ await waitForIndexedProducts(appContainer, [
+ { id: productId, restricted: true },
+ ])
const shippingProfile = await createShippingProfile(appContainer, {
name: `${opts.name} Profile ${tag}`,
diff --git a/integration-tests/http/product/store/product.spec.ts b/integration-tests/http/product/store/product.spec.ts
index 9bd1c25f4..e76bdf3bd 100644
--- a/integration-tests/http/product/store/product.spec.ts
+++ b/integration-tests/http/product/store/product.spec.ts
@@ -4,7 +4,11 @@ import {
ISalesChannelModuleService,
MedusaContainer,
} from "@medusajs/framework/types"
-import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import {
+ ContainerRegistrationKeys,
+ Modules,
+ ProductStatus,
+} from "@medusajs/framework/utils"
import { MercurModules } from "@mercurjs/types"
import {
adminHeaders,
@@ -13,6 +17,8 @@ import {
generateStoreHeaders,
} from "../../../helpers/create-admin-user"
import { createSellerUser } from "../../../helpers/create-seller-user"
+import { eventually } from "../../../helpers/eventually"
+import { waitForIndexedProducts } from "../../../helpers/wait-for-indexed-products"
jest.setTimeout(60000)
@@ -117,6 +123,14 @@ medusaIntegrationTestRunner({
[MercurModules.SELLER]: { seller_id: seller.id },
})
+ await waitForIndexedProducts(appContainer, [
+ {
+ id: product.id,
+ status: product.status,
+ restricted: true,
+ },
+ ])
+
return product
}
@@ -341,6 +355,104 @@ medusaIntegrationTestRunner({
})
})
+ describe("cached responses", () => {
+ const listIds = async () =>
+ (
+ await api.get(`/store/products?limit=100`, storeHeaders)
+ ).data.products.map((p: { id: string }) => p.id)
+
+ it("answers a plain product list with query.graph and an exact count", async () => {
+ const ids = [
+ (await createProduct(approvedSellerHeaders, { title: "Plain 1" })).id,
+ (await createProduct(approvedSellerHeaders, { title: "Plain 2" })).id,
+ (await createProduct(approvedSellerHeaders, { title: "Plain 3" })).id,
+ ]
+ const query = appContainer.resolve(
+ ContainerRegistrationKeys.QUERY
+ )
+ const indexSpy = jest.spyOn(query, "index")
+
+ const response = await api.get(
+ `/store/products?limit=1`,
+ storeHeaders
+ )
+
+ expect(indexSpy).not.toHaveBeenCalled()
+ indexSpy.mockRestore()
+ expect(response.data.products).toHaveLength(1)
+ expect(response.data.count).toEqual(ids.length)
+ })
+
+ it("stores the product list in the caching module", async () => {
+ await createProduct(approvedSellerHeaders, {
+ title: "Cache Probe",
+ })
+ await listIds()
+
+ const caching = appContainer.resolve(Modules.CACHING)
+ const cached = await caching.get({
+ tags: ["Product:list:*"],
+ })
+ expect(cached).toBeTruthy()
+ })
+
+ it("lists a product created after the list was cached", async () => {
+ const first = await createProduct(approvedSellerHeaders, {
+ title: "Cached First",
+ })
+ expect(await listIds()).toEqual([first.id])
+ expect(await listIds()).toEqual([first.id])
+
+ const second = await createProduct(approvedSellerHeaders, {
+ title: "Cached Second",
+ })
+
+ expect((await listIds()).sort()).toEqual(
+ [first.id, second.id].sort()
+ )
+ })
+
+ it("drops an unpublished product from the cached list", async () => {
+ const product = await createProduct(approvedSellerHeaders, {
+ title: "Cached Unpublish",
+ })
+ expect(await listIds()).toContain(product.id)
+
+ await productModuleService.updateProducts(product.id, {
+ status: ProductStatus.DRAFT,
+ })
+ await waitForIndexedProducts(appContainer, [
+ { id: product.id, status: "draft", restricted: true },
+ ])
+
+ expect(await listIds()).not.toContain(product.id)
+ })
+
+ it("serves an updated title from the cached detail route", async () => {
+ const product = await createProduct(approvedSellerHeaders, {
+ title: "Detail Before",
+ })
+ const titleOf = async () =>
+ (
+ await api.get(
+ `/store/products/${product.id}`,
+ storeHeaders
+ )
+ ).data.product.title
+
+ expect(await titleOf()).toEqual("Detail Before")
+ expect(await titleOf()).toEqual("Detail Before")
+
+ await productModuleService.updateProducts(product.id, {
+ title: "Detail After",
+ })
+
+ await eventually(async () => {
+ expect(await titleOf()).toEqual("Detail After")
+ })
+ })
+ })
+
describe("GET /store/products/:id", () => {
it("should retrieve a single published product from an approved seller", async () => {
const product = await createProduct(approvedSellerHeaders, {
diff --git a/integration-tests/http/product/vendor/product.spec.ts b/integration-tests/http/product/vendor/product.spec.ts
index ae3fd802a..64de4c866 100644
--- a/integration-tests/http/product/vendor/product.spec.ts
+++ b/integration-tests/http/product/vendor/product.spec.ts
@@ -1,5 +1,5 @@
import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
import { MedusaContainer } from "@medusajs/framework/types"
import {
@@ -12,6 +12,7 @@ import {
createAdminUser,
} from "../../../helpers/create-admin-user"
import { createSellerUser } from "../../../helpers/create-seller-user"
+import { waitForIndexedProducts } from "../../../helpers/wait-for-indexed-products"
import {
AttributeType,
MercurModules,
@@ -377,6 +378,7 @@ medusaIntegrationTestRunner({
describe("Vendor - product list scoping", () => {
let appContainer: MedusaContainer
let sellerA: any
+ let sellerB: any
let headersA: any
let headersB: any
@@ -396,6 +398,7 @@ medusaIntegrationTestRunner({
name: "Scope B Store",
})
headersB = b.headers
+ sellerB = b.seller
})
const createProduct = async (
@@ -410,7 +413,11 @@ medusaIntegrationTestRunner({
created_by: createdBy,
},
})
- return (result as { id: string }[])[0].id
+ const id = (result as { id: string }[])[0].id
+ await waitForIndexedProducts(appContainer, [
+ { id, status, restricted: !!sellerIds?.length },
+ ])
+ return id
}
it("scopes the vendor list to the seller's own proposed products plus published", async () => {
@@ -497,6 +504,171 @@ medusaIntegrationTestRunner({
expect(stillThere.data.product.title).toEqual("A Draft")
})
+ it("applies the same scoping when a category filter forces the graph fallback", async () => {
+ const productModule = appContainer.resolve(Modules.PRODUCT)
+ const [category] = await productModule.createProductCategories([
+ { name: "Fallback Category", is_active: true },
+ ])
+
+ const create = async (
+ title: string,
+ status: string,
+ createdBy: string,
+ sellerIds?: string[]
+ ) => {
+ const { result } = await createProductsWorkflow(appContainer).run({
+ input: {
+ products: [
+ {
+ title,
+ status,
+ seller_ids: sellerIds,
+ category_ids: [category.id],
+ } as any,
+ ],
+ created_by: createdBy,
+ },
+ })
+ return (result as { id: string }[])[0].id
+ }
+
+ const open = await create("Fallback Open", "published", "other-actor")
+ const restrictedToA = await create(
+ "Fallback Restricted",
+ "published",
+ "other-actor",
+ [sellerA.id]
+ )
+ const proposedByA = await create("Fallback Proposed", "proposed", sellerA.id)
+
+ const asA = await api.get(
+ `/vendor/products?category_id=${category.id}&limit=100`,
+ headersA
+ )
+ expect(asA.data.products.map((p: { id: string }) => p.id).sort()).toEqual(
+ [open, restrictedToA, proposedByA].sort()
+ )
+
+ const asB = await api.get(
+ `/vendor/products?category_id=${category.id}&limit=100`,
+ headersB
+ )
+ expect(asB.data.products.map((p: { id: string }) => p.id)).toEqual([open])
+ expect(asB.data.count).toEqual(1)
+ })
+
+ it("paginates the index-backed list with a count that is exact on the last page", async () => {
+ const ids = [
+ await createProduct("CountProbe One", "published", "other-actor"),
+ await createProduct("CountProbe Two", "published", "other-actor"),
+ await createProduct("CountProbe Three", "published", "other-actor"),
+ ]
+
+ const idFilter = ids.map((id) => `id[]=${id}`).join("&")
+
+ const first = await api.get(`/vendor/products?${idFilter}&limit=2`, headersA)
+ expect(first.data.products).toHaveLength(2)
+ expect(first.data.count).toEqual(3)
+
+ const last = await api.get(
+ `/vendor/products?${idFilter}&limit=2&offset=2`,
+ headersA
+ )
+ expect(last.data.products).toHaveLength(1)
+ expect(last.data.count).toEqual(3)
+
+ const seen = [...first.data.products, ...last.data.products].map(
+ (p: { id: string }) => p.id
+ )
+ expect(seen.sort()).toEqual([...ids].sort())
+ })
+
+ it("matches a partial word in q, as before the index engine", async () => {
+ const shirt = await createProduct("Linen Shirt", "published", "other-actor")
+ await createProduct("Wool Scarf", "published", "other-actor")
+
+ const response = await api.get("/vendor/products?q=Shi", headersA)
+
+ expect(response.data.products.map((p: { id: string }) => p.id)).toEqual([
+ shirt,
+ ])
+ })
+
+ describe("cached list invalidation", () => {
+ const listIds = async (headers: any) =>
+ (await api.get("/vendor/products?limit=100", headers)).data.products.map(
+ (p: { id: string }) => p.id
+ )
+
+ it("drops a product from a cached list once it is restricted to another seller", async () => {
+ const productId = await createProduct("Cache Restrict", "published", "other-actor")
+
+ expect(await listIds(headersB)).toContain(productId)
+ expect(await listIds(headersB)).toContain(productId)
+
+ await appContainer.resolve(ContainerRegistrationKeys.LINK).create({
+ [Modules.PRODUCT]: { product_id: productId },
+ [MercurModules.SELLER]: { seller_id: sellerA.id },
+ })
+ await waitForIndexedProducts(appContainer, [
+ { id: productId, status: "published", restricted: true },
+ ])
+
+ expect(await listIds(headersB)).not.toContain(productId)
+ expect(await listIds(headersA)).toContain(productId)
+ })
+
+ it("serves a product update instead of the cached list entry", async () => {
+ const productId = await createProduct("Cache Before", "published", "other-actor")
+ const titleOf = async () =>
+ (await api.get("/vendor/products?limit=100", headersA)).data.products.find(
+ (p: { id: string }) => p.id === productId
+ )?.title
+
+ expect(await titleOf()).toEqual("Cache Before")
+
+ await appContainer
+ .resolve(Modules.PRODUCT)
+ .updateProducts(productId, { title: "Cache After" })
+ await waitForIndexedProducts(appContainer, [
+ { id: productId, title: "Cache After", restricted: false },
+ ])
+
+ expect(await titleOf()).toEqual("Cache After")
+ })
+ })
+
+ it("serves the seller-scoped list through the index engine", async () => {
+ await createProduct("Index Path", "published", "other-actor")
+ const query = appContainer.resolve(ContainerRegistrationKeys.QUERY)
+ const indexSpy = jest.spyOn(query, "index")
+
+ await api.get("/vendor/products?limit=5", headersA)
+
+ expect(indexSpy).toHaveBeenCalled()
+ indexSpy.mockRestore()
+ })
+
+ it("returns the exact visible count on a full page, not the planner estimate", async () => {
+ const visible = [
+ await createProduct("Exact Open 1", "published", "other-actor"),
+ await createProduct("Exact Open 2", "published", "other-actor"),
+ await createProduct("Exact Allowlisted", "published", "other-actor", [
+ sellerA.id,
+ ]),
+ await createProduct("Exact Own Draft", "draft", sellerA.id),
+ await createProduct("Exact Own Proposed", "proposed", sellerA.id),
+ ]
+ await createProduct("Exact Hidden Restricted", "published", "other-actor", [
+ sellerB.id,
+ ])
+ await createProduct("Exact Hidden Draft", "draft", "other-actor")
+
+ const page = await api.get("/vendor/products?limit=2", headersA)
+ expect(page.data.products).toHaveLength(2)
+ expect(page.data.count).toEqual(visible.length)
+ })
+
it("hides a published product from its creator once restricted to other sellers", async () => {
const b = await createSellerUser(appContainer, {
diff --git a/integration-tests/http/seller/admin/seller.spec.ts b/integration-tests/http/seller/admin/seller.spec.ts
index cb97102d8..9ba28f88e 100644
--- a/integration-tests/http/seller/admin/seller.spec.ts
+++ b/integration-tests/http/seller/admin/seller.spec.ts
@@ -1,5 +1,10 @@
import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
-import { MedusaContainer } from "@medusajs/framework/types"
+import {
+ IEventBusModuleService,
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { Modules } from "@medusajs/framework/utils"
+import { eventually } from "../../../helpers/eventually"
import {
adminHeaders,
createAdminUser,
@@ -48,6 +53,58 @@ medusaIntegrationTestRunner({
memberC = resultC.member
})
+ describe("seller entity events", () => {
+ it("emits seller.seller.created / updated and lands the seller in the index", async () => {
+ const eventBus = appContainer.resolve<IEventBusModuleService>(
+ Modules.EVENT_BUS
+ )
+ const events: { name: string; id?: string }[] = []
+ eventBus.subscribe("*", async (event) => {
+ if (event.name.startsWith("seller.seller.")) {
+ events.push({
+ name: event.name,
+ id: (event.data as { id?: string } | undefined)?.id,
+ })
+ }
+ })
+
+ const created = await api.post(
+ `/admin/sellers`,
+ {
+ name: "Evented Seller",
+ email: "[email protected]",
+ currency_code: "usd",
+ member: { email: "[email protected]" },
+ },
+ adminHeaders
+ )
+ const sellerId = created.data.seller.id
+
+ await api.post(
+ `/admin/sellers/${sellerId}`,
+ { name: "Evented Seller Renamed" },
+ adminHeaders
+ )
+
+ await eventually(
+ async () => {
+ expect(events).toEqual(
+ expect.arrayContaining([
+ { name: "seller.seller.created", id: sellerId },
+ { name: "seller.seller.updated", id: sellerId },
+ ])
+ )
+ const { rows } = await dbConnection.raw(
+ `select id from index_data where name = 'Seller' and id = ?`,
+ [sellerId]
+ )
+ expect(rows).toHaveLength(1)
+ },
+ { timeout: 15000 }
+ )
+ })
+ })
+
describe("POST /admin/sellers", () => {
it("should create a seller with required fields", async () => {
const response = await api.post(
diff --git a/packages/core/src/api/admin/products/route.ts b/packages/core/src/api/admin/products/route.ts
index 8aba13cdc..2f3b1e569 100644
--- a/packages/core/src/api/admin/products/route.ts
+++ b/packages/core/src/api/admin/products/route.ts
@@ -9,6 +9,7 @@ import { HttpTypes } from "@mercurjs/types"
import { createProductsWorkflow } from "../../../workflows/product/workflows/create-products"
import {
enrichProductAttributes,
+ listProducts,
wrapProductVariantsWithOffers,
} from "../../utils"
import { AdminCreateProductType, AdminGetProductsParamsType } from "./validators"
@@ -17,8 +18,6 @@ export const GET = async (
req: AuthenticatedMedusaRequest<AdminGetProductsParamsType>,
res: MedusaResponse<HttpTypes.AdminProductListResponse>
) => {
- const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
-
const withOffers = req.queryConfig.fields.some((field) =>
field.includes("variants.offers")
)
@@ -35,11 +34,15 @@ export const GET = async (
filters.$and = [...and, { variants: { sku } }]
}
- const { data: products, metadata } = await query.graph({
- entity: "product",
+ const { products, count, estimate_count, offset, limit } = await listProducts<
+ HttpTypes.AdminProductListResponse["products"][number]
+ >(req.scope, {
fields: req.queryConfig.fields,
filters,
pagination: req.queryConfig.pagination,
+ withDeleted: req.queryConfig.withDeleted,
+ cache: { ttl: 60 },
+ exactCount: true,
})
await enrichProductAttributes(req.scope, products as any[])
@@ -51,12 +54,7 @@ export const GET = async (
)
}
- res.json({
- products,
- count: metadata?.count ?? 0,
- offset: metadata?.skip ?? 0,
- limit: metadata?.take ?? 0,
- })
+ res.json({ products, count, estimate_count, offset, limit })
}
export const POST = async (
diff --git a/packages/core/src/api/store/offers/helpers.ts b/packages/core/src/api/store/offers/helpers.ts
index 590ec07d9..031cd69c3 100644
--- a/packages/core/src/api/store/offers/helpers.ts
+++ b/packages/core/src/api/store/offers/helpers.ts
@@ -247,7 +247,14 @@ export const wrapOffersWithInventoryQuantityForSalesChannel = async (
fields: ["stock_locations.id"],
filters: { id: channelToUse },
},
- { cache: { enable: true } }
+ {
+ cache: {
+ enable: true,
+ // Linking a location to the channel only clears this link tag.
+ tags: ["LinkSalesChannelStockLocation:list:*"],
+ computeAutomaticTags: true,
+ },
+ }
)
const channelLocationIds = new Set<string>(
diff --git a/packages/core/src/api/store/products/[id]/route.ts b/packages/core/src/api/store/products/[id]/route.ts
index c57165174..f1e268d68 100644
--- a/packages/core/src/api/store/products/[id]/route.ts
+++ b/packages/core/src/api/store/products/[id]/route.ts
@@ -48,7 +48,16 @@ export const GET = async (req: MedusaStoreRequest, res: MedusaResponse) => {
fields: req.queryConfig.fields,
filters: { ...productFilters, id: req.params.id },
},
- { cache: { enable: true }, locale: req.locale }
+ {
+ // A miss (unpublished or not yet created) caches an empty result with no
+ // automatic tags; the list tag lets the next product write clear it.
+ cache: {
+ enable: true,
+ tags: ["Product:list:*"],
+ computeAutomaticTags: true,
+ },
+ locale: req.locale,
+ }
)
if (!product) {
diff --git a/packages/core/src/api/store/products/route.ts b/packages/core/src/api/store/products/route.ts
index 5bfd2a034..da321ff85 100644
--- a/packages/core/src/api/store/products/route.ts
+++ b/packages/core/src/api/store/products/route.ts
@@ -2,17 +2,14 @@ import {
MedusaResponse,
MedusaStoreRequest,
} from "@medusajs/framework/http"
-import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
-
import {
enrichProductAttributes,
+ listProducts,
wrapProductVariantsWithOfferPrice,
} from "../../utils"
import { splitComputedVariantFields } from "./helpers"
export const GET = async (req: MedusaStoreRequest, res: MedusaResponse) => {
- const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
-
// `variants.calculated_price` / `variants.offer_id` are computed from the
// cheapest offer post-query, not graph columns — strip them before the read.
const { fields, withCalculatedPrice } = splitComputedVariantFields(
@@ -20,24 +17,27 @@ export const GET = async (req: MedusaStoreRequest, res: MedusaResponse) => {
)
req.queryConfig.fields = fields
- // region_id / currency_code are consumed by setPricingContext only.
- // The Product entity has neither column, so passing them through to
- // query.graph raises `Trying to query by not existing property
- // Product.region_id`.
+ // Pricing-context keys feed setPricingContext / the offer-price wrap, not
+ // product columns: query.graph errors on region_id, and the index rejects
+ // every non-indexed key (`Field country_code is not indexed`).
const {
region_id: _r,
currency_code: _c,
+ country_code: _cc,
+ province: _p,
+ cart_id: _cart,
...productFilters
} = (req.filterableFields ?? {}) as Record<string, unknown>
- const { data: products, metadata } = await query.graph(
+ const { products, count, estimate_count, offset, limit } = await listProducts(
+ req.scope,
{
- entity: "product",
fields: req.queryConfig.fields,
filters: productFilters,
pagination: req.queryConfig.pagination,
- },
- { cache: { enable: true }, locale: req.locale }
+ locale: req.locale,
+ cache: { ttl: 300 },
+ }
)
await enrichProductAttributes(req.scope, products as any[])
@@ -46,10 +46,5 @@ export const GET = async (req: MedusaStoreRequest, res: MedusaResponse) => {
await wrapProductVariantsWithOfferPrice(req, products as any[])
}
- res.json({
- products,
- count: metadata?.count ?? 0,
- offset: metadata?.skip ?? 0,
- limit: metadata?.take ?? 0,
- })
+ res.json({ products, count, estimate_count, offset, limit })
}
diff --git a/packages/core/src/api/utils/ensure-seller-middleware.ts b/packages/core/src/api/utils/ensure-seller-middleware.ts
index 32cbde2d9..14d5ec026 100644
--- a/packages/core/src/api/utils/ensure-seller-middleware.ts
+++ b/packages/core/src/api/utils/ensure-seller-middleware.ts
@@ -30,17 +30,16 @@ export async function ensureSellerMiddleware(
const memberId = req.auth_context.actor_id
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
- const { data: sellerMembers } = await query.graph(
- {
- entity: "seller_member",
- fields: ["id", "seller_id", "member_id", "role_id", "seller.*"],
- filters: {
- seller_id: sellerId,
- member_id: memberId,
- },
+ // Not cached: an authorization read must reflect a removed member or a
+ // suspended seller on the very next request, not after a TTL.
+ const { data: sellerMembers } = await query.graph({
+ entity: "seller_member",
+ fields: ["id", "seller_id", "member_id", "role_id", "seller.*"],
+ filters: {
+ seller_id: sellerId,
+ member_id: memberId,
},
- { cache: { enable: true } }
- )
+ })
if (!sellerMembers.length) {
return next(
diff --git a/packages/core/src/api/utils/index.ts b/packages/core/src/api/utils/index.ts
index 1c88b3c49..f2343f3f8 100644
--- a/packages/core/src/api/utils/index.ts
+++ b/packages/core/src/api/utils/index.ts
@@ -9,5 +9,6 @@ export * from "./format-product-attributes"
export * from "./product-attribute-fields"
export * from "./filter-attributes-by-category-link"
export * from "./offers"
+export * from "./list-products"
export * from "./split-order-payment-status"
export * from "./restrict-vendor-fields"
diff --git a/packages/core/src/api/utils/list-products.ts b/packages/core/src/api/utils/list-products.ts
new file mode 100644
index 000000000..9f801d310
--- /dev/null
+++ b/packages/core/src/api/utils/list-products.ts
@@ -0,0 +1,340 @@
+import {
+ ContainerRegistrationKeys,
+ isPresent,
+ Modules,
+ promiseAll,
+ useCache,
+} from "@medusajs/framework/utils"
+import type {
+ IIndexService,
+ IndexQueryConfig,
+ MedusaContainer,
+} from "@medusajs/framework/types"
+
+type IndexedShape = { [key: string]: true | IndexedShape }
+
+// The index rejects any key outside its schema, so only these reach it. `q` is
+// left out on purpose: the index matches whole tokens (plainto_tsquery) where
+// query.graph matches substrings, and search must not change with the engine.
+const INDEXED_PRODUCT: IndexedShape = {
+ id: true,
+ title: true,
+ handle: true,
+ status: true,
+ type_id: true,
+ collection_id: true,
+ is_giftcard: true,
+ external_id: true,
+ created_at: true,
+ updated_at: true,
+ variants: {
+ id: true,
+ sku: true,
+ product_id: true,
+ prices: {
+ id: true,
+ amount: true,
+ currency_code: true,
+ price_list_id: true,
+ },
+ },
+ sales_channels: { id: true, is_disabled: true },
+ product_seller: { id: true },
+}
+
+const CROSS_MODULE_KEYS = ["product_seller", "sales_channels"]
+const CROSS_MODULE_VARIANT_KEYS = ["prices"]
+const LOGICAL_OPERATORS = ["$and", "$or", "$not"]
+const INDEX_LIST_CACHE_TTL = 5
+
+const isPlainObject = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" &&
+ value !== null &&
+ !Array.isArray(value) &&
+ !(value instanceof Date)
+
+const needsIndex = (filters: Record<string, unknown>): boolean =>
+ Object.entries(filters).some(([key, value]) => {
+ if (LOGICAL_OPERATORS.includes(key)) {
+ const entries = Array.isArray(value) ? value : [value]
+ return entries.some((entry) => isPlainObject(entry) && needsIndex(entry))
+ }
+ if (CROSS_MODULE_KEYS.includes(key)) {
+ return true
+ }
+ return (
+ key === "variants" &&
+ isPlainObject(value) &&
+ Object.keys(value).some((k) => CROSS_MODULE_VARIANT_KEYS.includes(k))
+ )
+ })
+
+const isIndexable = (
+ filters: Record<string, unknown>,
+ shape: IndexedShape
+): boolean =>
+ Object.entries(filters).every(([key, value]) => {
+ if (value === undefined) {
+ return true
+ }
+
+ if (LOGICAL_OPERATORS.includes(key)) {
+ const entries = Array.isArray(value) ? value : [value]
+ return entries.every(
+ (entry) => isPlainObject(entry) && isIndexable(entry, shape)
+ )
+ }
+
+ const node = shape[key]
+ if (!node) {
+ return false
+ }
+ if (node === true) {
+ return true
+ }
+
+ return isPlainObject(value) && isIndexable(value, node)
+ })
+
+const isOrderIndexable = (order: Record<string, unknown> | undefined) =>
+ !order ||
+ Object.keys(order).every((path) => {
+ let node: true | IndexedShape | undefined = INDEXED_PRODUCT
+ for (const segment of path.split(".")) {
+ if (!node || node === true) {
+ return false
+ }
+ node = node[segment]
+ }
+ return node === true
+ })
+
+const toIndexFilters = (
+ filters: Record<string, unknown>
+): Record<string, unknown> => {
+ const {
+ sales_channel_id: salesChannelId,
+ price_list_id: priceListId,
+ ...rest
+ } = filters
+
+ const next: Record<string, unknown> = { ...rest }
+
+ if (isPresent(salesChannelId)) {
+ next.sales_channels = {
+ ...(isPlainObject(next.sales_channels) ? next.sales_channels : {}),
+ id: salesChannelId,
+ }
+ }
+
+ if (isPresent(priceListId)) {
+ const variants = isPlainObject(next.variants) ? next.variants : {}
+ const prices = isPlainObject(variants.prices) ? variants.prices : {}
+ next.variants = { ...variants, prices: { ...prices, price_list_id: priceListId } }
+ }
+
+ return next
+}
+
+// Checked through the container, not FeatureFlag: core and the host can load
+// separate @medusajs/framework copies with separate flag routers.
+const isIndexEngineEnabled = (scope: MedusaContainer) =>
+ !!scope.resolve(Modules.INDEX, { allowUnregistered: true })
+
+type Pagination = {
+ skip?: number
+ take?: number
+ order?: Record<string, unknown>
+}
+
+// query.graph cannot filter on linked-module fields, hence one shape per engine.
+export type ProductVisibility = {
+ index: Record<string, unknown>
+ graph: () => Promise<Record<string, unknown>>
+}
+
+const withClause = (
+ filters: Record<string, unknown>,
+ clause: Record<string, unknown> | undefined
+) => {
+ if (!clause) {
+ return filters
+ }
+ const existing = Array.isArray(filters.$and) ? filters.$and : []
+ return { ...filters, $and: [...existing, clause] }
+}
+
+type ListProductsCache = {
+ ttl?: number
+ tags?: string[]
+}
+
+type ListProductsInput = {
+ fields: string[]
+ filters?: Record<string, unknown>
+ visibility?: ProductVisibility
+ pagination?: Pagination
+ withDeleted?: boolean
+ locale?: string
+ cache?: ListProductsCache
+ exactCount?: boolean
+}
+
+type ListProductsResult<T> = {
+ products: T[]
+ count: number
+ estimate_count?: number
+ offset: number
+ limit: number
+}
+
+// Automatic tags come from the returned rows, so an empty page has none, and
+// variant writes only clear ProductVariant tags.
+const listCacheTags = (cache: ListProductsCache | undefined) => [
+ "Product:list:*",
+ "ProductVariant:list:*",
+ ...(cache?.tags ?? []),
+]
+
+const toQueryOptions = (
+ cache: ListProductsCache | undefined,
+ locale: string | undefined,
+ ttl: number | undefined
+) => ({
+ ...(cache
+ ? {
+ cache: {
+ enable: true,
+ ...(ttl !== undefined ? { ttl } : {}),
+ tags: listCacheTags(cache),
+ computeAutomaticTags: true,
+ },
+ }
+ : {}),
+ ...(locale ? { locale } : {}),
+})
+
+const reconcileCount = (
+ estimate: number,
+ skip: number,
+ take: number | undefined,
+ returned: number
+) => {
+ if (take === undefined || returned < take) {
+ return skip + returned
+ }
+ return Math.max(estimate, skip + returned + 1)
+}
+
+// query.index only reports the planner estimate, which undercounts JSONB
+// filters badly. This is the ids-only call query.index makes, without paging.
+const countIndexedProducts = async (
+ scope: MedusaContainer,
+ filters: Record<string, unknown>,
+ cache: ListProductsCache | undefined,
+ ttl: number
+): Promise<number> => {
+ const { count } = await useCache(
+ async () => {
+ const { data } = await scope
+ .resolve<IIndexService>(Modules.INDEX)
+ .query({
+ fields: ["product.id"],
+ filters: { product: filters } as IndexQueryConfig<"product">["filters"],
+ idsOnly: true,
+ })
+ return { count: data.length }
+ },
+ {
+ enable: !!cache,
+ key: ["mercur:product-count", filters],
+ tags: listCacheTags(cache),
+ ttl,
+ container: scope,
+ }
+ )
+ return count
+}
+
+export const listProducts = async <T = Record<string, unknown>>(
+ scope: MedusaContainer,
+ {
+ fields,
+ filters = {},
+ visibility,
+ pagination,
+ withDeleted,
+ locale,
+ cache,
+ exactCount,
+ }: ListProductsInput
+): Promise<ListProductsResult<T>> => {
+ const query = scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const indexFilters = withClause(toIndexFilters(filters), visibility?.index)
+
+ if (
+ !withDeleted &&
+ needsIndex(indexFilters) &&
+ isIndexEngineEnabled(scope) &&
+ isIndexable(indexFilters, INDEXED_PRODUCT) &&
+ isOrderIndexable(pagination?.order)
+ ) {
+ // One event clears the cache and starts the async index sync, so a request
+ // in between re-caches pre-write index state; the TTL bounds that.
+ const indexTtl = Math.min(
+ cache?.ttl ?? INDEX_LIST_CACHE_TTL,
+ INDEX_LIST_CACHE_TTL
+ )
+
+ const [{ data, metadata }, exact] = await promiseAll([
+ query.index(
+ {
+ entity: "product",
+ fields,
+ filters: indexFilters,
+ pagination,
+ },
+ toQueryOptions(cache, locale, indexTtl)
+ ),
+ exactCount
+ ? countIndexedProducts(scope, indexFilters, cache, indexTtl)
+ : undefined,
+ ])
+
+ const skip = metadata?.skip ?? pagination?.skip ?? 0
+ const take = metadata?.take ?? pagination?.take
+ const estimate = metadata?.estimate_count ?? 0
+
+ return {
+ products: data as T[],
+ count: exact ?? reconcileCount(estimate, skip, take, data.length),
+ estimate_count: estimate,
+ offset: skip,
+ limit: take ?? data.length,
+ }
+ }
+
+ const graphFilters = withClause(
+ filters,
+ visibility ? await visibility.graph() : undefined
+ )
+
+ const { data, metadata } = await query.graph(
+ {
+ entity: "product",
+ fields,
+ filters: graphFilters,
+ pagination,
+ withDeleted,
+ },
+ toQueryOptions(cache, locale, cache?.ttl)
+ )
+
+ return {
+ products: data as T[],
+ count: metadata?.count ?? 0,
+ offset: metadata?.skip ?? 0,
+ limit: metadata?.take ?? 0,
+ }
+}
diff --git a/packages/core/src/api/utils/offers.ts b/packages/core/src/api/utils/offers.ts
index f6388370c..6f8d9b0eb 100644
--- a/packages/core/src/api/utils/offers.ts
+++ b/packages/core/src/api/utils/offers.ts
@@ -125,14 +125,14 @@ export const applyOfferedProductsFilter = async (
const { data: offers } = await query.graph({
entity: "offer",
- fields: ["variant_id"],
+ fields: ["product_id"],
filters: sellerId ? { seller_id: sellerId } : {},
})
- const variantIds = Array.from(
+ const productIds = Array.from(
new Set(
offers
- .map((offer: { variant_id: string | null }) => offer.variant_id)
+ .map((offer: { product_id: string | null }) => offer.product_id)
.filter((id: string | null): id is string => Boolean(id))
)
)
@@ -140,7 +140,7 @@ export const applyOfferedProductsFilter = async (
const existingAnd = (req.filterableFields.$and as object[] | undefined) ?? []
req.filterableFields.$and = [
...existingAnd,
- { variants: { id: variantIds.length ? variantIds : ["__none__"] } },
+ { id: productIds.length ? productIds : ["__none__"] },
]
return next()
diff --git a/packages/core/src/api/utils/sellers.ts b/packages/core/src/api/utils/sellers.ts
index a7e997596..1bf9f42cb 100644
--- a/packages/core/src/api/utils/sellers.ts
+++ b/packages/core/src/api/utils/sellers.ts
@@ -20,7 +20,15 @@ export const resolveVisibleSellerIds = async (
{ $or: [{ closed_to: null }, { closed_to: { $lt: now } }] },
],
},
- }, { cache: { enable: true } })
+ }, {
+ cache: {
+ enable: true,
+ // An empty result carries no automatic tags, so without the list tag it
+ // would survive the next seller approval until its TTL.
+ tags: ["Seller:list:*"],
+ computeAutomaticTags: true,
+ },
+ })
return visibleSellers.map((s: { id: string }) => s.id)
}
diff --git a/packages/core/src/api/vendor/products/helpers.ts b/packages/core/src/api/vendor/products/helpers.ts
index 0a04b4a20..408174a2d 100644
--- a/packages/core/src/api/vendor/products/helpers.ts
+++ b/packages/core/src/api/vendor/products/helpers.ts
@@ -4,7 +4,9 @@ import {
promiseAll,
} from "@medusajs/framework/utils"
import type { MedusaContainer } from "@medusajs/framework/types"
-import { ProductChangeActionType } from "@mercurjs/types"
+import { ProductChangeActionType, ProductStatus } from "@mercurjs/types"
+
+import type { ProductVisibility } from "../../utils/list-products"
export const getSellerOwnedProductIds = async (
scope: MedusaContainer,
@@ -74,21 +76,92 @@ export const getProductIdsRestrictedFromSeller = async (
return Array.from(restricted)
}
-export const getProductStatus = async (
+export const getSellerProductVisibility = async (
scope: MedusaContainer,
+ sellerId: string
+): Promise<ProductVisibility> => {
+ const query = scope.resolve(ContainerRegistrationKeys.QUERY)
+
+ const [ownProductIds, { data: allowlistLinks }] = await promiseAll([
+ getSellerOwnedProductIds(scope, sellerId),
+ query.graph({
+ entity: "product_seller",
+ fields: ["product_id"],
+ filters: { seller_id: sellerId },
+ }),
+ ])
+
+ const ownSubmissions = ownProductIds.length
+ ? [
+ {
+ id: ownProductIds,
+ status: { $in: [ProductStatus.DRAFT, ProductStatus.PROPOSED] },
+ },
+ ]
+ : []
+ const allowlistedIds = (allowlistLinks as { product_id: string | null }[])
+ .map((link) => link.product_id)
+ .filter((id): id is string => !!id)
+
+ return {
+ // A bare `null` compiles to `= NULL` in the index query builder, hence `$eq`.
+ index: {
+ $or: [
+ ...ownSubmissions,
+ {
+ status: ProductStatus.PUBLISHED,
+ product_seller: { id: { $eq: null } },
+ },
+ ...(allowlistedIds.length
+ ? [{ status: ProductStatus.PUBLISHED, id: allowlistedIds }]
+ : []),
+ ],
+ },
+ graph: async () => {
+ const restrictedFromSellerIds = await getProductIdsRestrictedFromSeller(
+ scope,
+ sellerId
+ )
+ return {
+ $or: [
+ ...ownSubmissions,
+ {
+ status: ProductStatus.PUBLISHED,
+ id: { $nin: restrictedFromSellerIds },
+ },
+ ],
+ }
+ },
+ }
+}
+
+export const isProductVisibleToSeller = async (
+ scope: MedusaContainer,
+ sellerId: string,
productId: string
-): Promise<{ id: string; status: string } | undefined> => {
+): Promise<boolean> => {
const query = scope.resolve(ContainerRegistrationKeys.QUERY)
- const {
- data: [product],
- } = await query.graph({
- entity: "product",
- fields: ["id", "status"],
- filters: { id: productId },
- })
+ const [ownProductIds, restrictedFromSellerIds, { data: [product] }] =
+ await promiseAll([
+ getSellerOwnedProductIds(scope, sellerId, [productId]),
+ getProductIdsRestrictedFromSeller(scope, sellerId, [productId]),
+ query.graph({
+ entity: "product",
+ fields: ["id", "status"],
+ filters: { id: productId },
+ }),
+ ])
+
+ if (!product) {
+ return false
+ }
- return product
+ return (
+ ownProductIds.includes(productId) ||
+ (product.status === ProductStatus.PUBLISHED &&
+ !restrictedFromSellerIds.includes(productId))
+ )
}
export const ensureSellerOwnsProduct = async (
diff --git a/packages/core/src/api/vendor/products/middlewares.ts b/packages/core/src/api/vendor/products/middlewares.ts
index fe9e4c9d9..7937a401b 100644
--- a/packages/core/src/api/vendor/products/middlewares.ts
+++ b/packages/core/src/api/vendor/products/middlewares.ts
@@ -9,14 +9,8 @@ import {
validateAndTransformBody,
validateAndTransformQuery,
} from "@medusajs/framework"
-import { ProductStatus } from "@mercurjs/types"
-
import { applyOfferedProductsFilter } from "../../utils"
-import {
- getProductIdsRestrictedFromSeller,
- getProductStatus,
- getSellerOwnedProductIds,
-} from "./helpers"
+import { isProductVisibleToSeller } from "./helpers"
import {
vendorProductQueryConfig,
vendorProductVariantQueryConfig,
@@ -36,61 +30,19 @@ import {
import {
ContainerRegistrationKeys,
MedusaError,
- promiseAll,
} from "@medusajs/framework/utils"
-const applySellerProductLinkFilter = async (
- req: AuthenticatedMedusaRequest,
- _res: MedusaResponse,
- next: MedusaNextFunction
-) => {
- const sellerId = req.seller_context!.seller_id
-
- const [ownProductIds, restrictedFromSellerIds] = await promiseAll([
- getSellerOwnedProductIds(req.scope, sellerId),
- getProductIdsRestrictedFromSeller(req.scope, sellerId),
- ])
-
- req.filterableFields ??= {}
- const existingAnd = (req.filterableFields.$and as object[] | undefined) ?? []
- req.filterableFields.$and = [
- ...existingAnd,
- {
- $or: [
- {
- id: ownProductIds,
- status: { $in: [ProductStatus.DRAFT, ProductStatus.PROPOSED] },
- },
- {
- status: ProductStatus.PUBLISHED,
- id: { $nin: restrictedFromSellerIds },
- },
- ],
- },
- ]
-
- return next()
-}
-
const ensureProductVisibleToSeller = async (
req: AuthenticatedMedusaRequest,
_res: MedusaResponse,
next: MedusaNextFunction
) => {
- const sellerId = req.seller_context!.seller_id
const productId = req.params.id
-
- const [ownProductIds, restrictedFromSellerIds, product] = await promiseAll([
- getSellerOwnedProductIds(req.scope, sellerId, [productId]),
- getProductIdsRestrictedFromSeller(req.scope, sellerId, [productId]),
- getProductStatus(req.scope, productId),
- ])
-
- const visible =
- !!product &&
- (ownProductIds.includes(productId) ||
- (product.status === ProductStatus.PUBLISHED &&
- !restrictedFromSellerIds.includes(productId)))
+ const visible = await isProductVisibleToSeller(
+ req.scope,
+ req.seller_context!.seller_id,
+ productId
+ )
if (!visible) {
return next(
@@ -147,7 +99,6 @@ export const vendorProductsMiddlewares: MiddlewareRoute[] = [
VendorGetProductsParams,
vendorProductQueryConfig.list
),
- applySellerProductLinkFilter,
applyOfferedProductsFilter,
],
},
diff --git a/packages/core/src/api/vendor/products/route.ts b/packages/core/src/api/vendor/products/route.ts
index fad17d2c9..a38dd32da 100644
--- a/packages/core/src/api/vendor/products/route.ts
+++ b/packages/core/src/api/vendor/products/route.ts
@@ -12,15 +12,17 @@ import {
} from "../../../workflows/product/workflows/create-products"
import {
enrichProductAttributes,
+ listProducts,
wrapProductVariantsWithOffers,
} from "../../utils"
+import { getSellerProductVisibility } from "./helpers"
import { VendorCreateProductType, VendorGetProductsParamsType } from "./validators"
export const GET = async (
req: AuthenticatedMedusaRequest<VendorGetProductsParamsType>,
res: MedusaResponse<HttpTypes.VendorProductListResponse>
) => {
- const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
+ const sellerId = req.seller_context!.seller_id
const withOffers = req.queryConfig.fields.some((field) =>
field.includes("variants.offers")
@@ -31,11 +33,15 @@ export const GET = async (
)
}
- const { data: products, metadata } = await query.graph({
- entity: "product",
+ const { products, count, estimate_count, offset, limit } = await listProducts<
+ HttpTypes.VendorProductListResponse["products"][number]
+ >(req.scope, {
fields: req.queryConfig.fields,
filters: req.filterableFields,
+ visibility: await getSellerProductVisibility(req.scope, sellerId),
pagination: req.queryConfig.pagination,
+ cache: { ttl: 60, tags: ["LinkProductSeller:list:*"] },
+ exactCount: true,
})
await enrichProductAttributes(req.scope, products as any[])
@@ -44,16 +50,11 @@ export const GET = async (
await wrapProductVariantsWithOffers(
req.scope,
products as Parameters<typeof wrapProductVariantsWithOffers>[1],
- req.seller_context!.seller_id
+ sellerId
)
}
- res.json({
- products,
- count: metadata?.count ?? 0,
- offset: metadata?.skip ?? 0,
- limit: metadata?.take ?? 0,
- })
+ res.json({ products, count, estimate_count, offset, limit })
}
export const POST = async (
diff --git a/packages/core/src/api/vendor/regions/helpers.ts b/packages/core/src/api/vendor/regions/helpers.ts
index 1b6fc3ca4..16097a868 100644
--- a/packages/core/src/api/vendor/regions/helpers.ts
+++ b/packages/core/src/api/vendor/regions/helpers.ts
@@ -16,7 +16,15 @@ export const listSellerRegionIds = async (
filters: { seller_id: sellerId },
fields: ["region_id"],
},
- { cache: { enable: true } }
+ {
+ cache: {
+ enable: true,
+ // Assigning a region only emits LinkRegionSeller.attached, which clears
+ // nothing but this tag.
+ tags: ["LinkRegionSeller:list:*"],
+ computeAutomaticTags: true,
+ },
+ }
)
return links.map((link) => (link as { region_id: string }).region_id)
diff --git a/packages/core/src/api/vendor/sellers/select/route.ts b/packages/core/src/api/vendor/sellers/select/route.ts
index 3618a309b..87a61acfd 100644
--- a/packages/core/src/api/vendor/sellers/select/route.ts
+++ b/packages/core/src/api/vendor/sellers/select/route.ts
@@ -18,17 +18,15 @@ export const POST = async (
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
- const { data: sellerMembers } = await query.graph(
- {
- entity: "seller_member",
- fields: ["id", "seller_id", "member_id"],
- filters: {
- seller_id,
- member_id: memberId,
- },
+ // Not cached: membership decides which store the session may switch to.
+ const { data: sellerMembers } = await query.graph({
+ entity: "seller_member",
+ fields: ["id", "seller_id", "member_id"],
+ filters: {
+ seller_id,
+ member_id: memberId,
},
- { cache: { enable: true } }
- )
+ })
if (!sellerMembers.length) {
throw new MedusaError(
diff --git a/packages/core/src/links/product-seller-link.ts b/packages/core/src/links/product-seller-link.ts
index 3a42d265c..2a4565c62 100644
--- a/packages/core/src/links/product-seller-link.ts
+++ b/packages/core/src/links/product-seller-link.ts
@@ -10,6 +10,7 @@ export default defineLink(
{
linkable: SellerModule.linkable.seller,
isList: true,
+ filterable: ["id"],
},
{
database: {
diff --git a/packages/core/src/modules/product-edit/migrations/Migration20261103120000.ts b/packages/core/src/modules/product-edit/migrations/Migration20261103120000.ts
new file mode 100644
index 000000000..17c636fb9
--- /dev/null
+++ b/packages/core/src/modules/product-edit/migrations/Migration20261103120000.ts
@@ -0,0 +1,17 @@
+import { Migration } from "@medusajs/framework/mikro-orm/migrations"
+
+export class Migration20261103120000 extends Migration {
+ override async up(): Promise<void> {
+ this.addSql(`
+ CREATE INDEX IF NOT EXISTS "IDX_product_change_created_by"
+ ON "product_change" ("created_by")
+ WHERE "deleted_at" IS NULL;
+ `)
+ }
+
+ override async down(): Promise<void> {
+ this.addSql(`
+ DROP INDEX IF EXISTS "IDX_product_change_created_by";
+ `)
+ }
+}
diff --git a/packages/core/src/modules/product-edit/models/product-change.ts b/packages/core/src/modules/product-edit/models/product-change.ts
index 49f2c452d..9924d3c16 100644
--- a/packages/core/src/modules/product-edit/models/product-change.ts
+++ b/packages/core/src/modules/product-edit/models/product-change.ts
@@ -51,6 +51,12 @@ const ProductChange = model
unique: false,
where: "deleted_at IS NULL",
},
+ {
+ name: "IDX_product_change_created_by",
+ on: ["created_by"],
+ unique: false,
+ where: "deleted_at IS NULL",
+ },
])
export default ProductChange
diff --git a/packages/core/src/modules/seller/service.ts b/packages/core/src/modules/seller/service.ts
index 1d0be71fb..94be396c5 100644
--- a/packages/core/src/modules/seller/service.ts
+++ b/packages/core/src/modules/seller/service.ts
@@ -1,6 +1,13 @@
import { configManager } from "@medusajs/framework/config"
-import { Context, DAL, FindConfig, InternalModuleDeclaration } from "@medusajs/framework/types"
import {
+ Context,
+ DAL,
+ FindConfig,
+ InternalModuleDeclaration,
+ ModulesSdkTypes,
+} from "@medusajs/framework/types"
+import {
+ EmitEvents,
generateJwtToken,
InjectManager,
isValidHandle,
@@ -35,12 +42,18 @@ import {
SellerStatus,
} from "@mercurjs/types"
+type SellerInput = Record<string, unknown> & {
+ name?: string
+ handle?: string | null
+}
+
const DEFAULT_INVITE_VALID_DURATION_SECONDS = 60 * 60 * 24 * 7 // 7 days
type InjectedDependencies = {
orderGroupRepository: OrderGroupRepository
sellerStatisticsRepository: SellerStatisticsRepository
baseRepository: DAL.RepositoryService
+ sellerService: ModulesSdkTypes.IMedusaInternalService<typeof Seller>
}
class SellerModuleService extends MedusaService({
@@ -56,6 +69,9 @@ class SellerModuleService extends MedusaService({
protected readonly orderGroupRepository_: OrderGroupRepository
protected readonly sellerStatisticsRepository_: SellerStatisticsRepository
protected readonly baseRepository_: DAL.RepositoryService
+ protected readonly sellerService_: ModulesSdkTypes.IMedusaInternalService<
+ typeof Seller
+ >
protected readonly options_: SellerModuleOptions
constructor(
@@ -63,6 +79,7 @@ class SellerModuleService extends MedusaService({
orderGroupRepository,
sellerStatisticsRepository,
baseRepository,
+ sellerService,
}: InjectedDependencies,
protected readonly moduleDeclaration?: InternalModuleDeclaration,
) {
@@ -72,6 +89,7 @@ class SellerModuleService extends MedusaService({
this.orderGroupRepository_ = orderGroupRepository
this.sellerStatisticsRepository_ = sellerStatisticsRepository
this.baseRepository_ = baseRepository
+ this.sellerService_ = sellerService
const opts = (moduleDeclaration?.options as SellerModuleOptions) ?? {}
this.options_ = {
@@ -106,33 +124,41 @@ class SellerModuleService extends MedusaService({
}
}
- @InjectTransactionManager()
- // @ts-ignore
+ // Entity events are only queued when the context carries a message aggregator,
+ // so overrides of generated methods need @EmitEvents to emit seller.seller.*.
+ @InjectManager()
+ @EmitEvents()
+ // @ts-expect-error
async createSellers<T extends any | any[]>(
data: T,
- sharedContext?: Context,
+ @MedusaContext() sharedContext: Context = {},
): Promise<T extends any[] ? SellerDTO[] : SellerDTO> {
- const input = (Array.isArray(data) ? data : [data]).map((seller) => {
- this.validateSellerData_(seller)
-
- if (!seller.handle && seller.name) {
- seller.handle = toHandle(seller.name)
- }
-
- return seller
- })
-
- const result = await super.createSellers(input, sharedContext)
+ const sellers = await this.sellerService_.create(
+ this.prepareSellerInput_(data),
+ sharedContext,
+ )
+ const result = await this.baseRepository_.serialize<SellerDTO[]>(sellers)
return (Array.isArray(data) ? result : result[0]) as any
}
- @InjectTransactionManager()
- // @ts-ignore
+ @InjectManager()
+ @EmitEvents()
+ // @ts-expect-error
async updateSellers<T extends any | any[]>(
data: T,
- sharedContext?: Context,
+ @MedusaContext() sharedContext: Context = {},
): Promise<T extends any[] ? SellerDTO[] : SellerDTO> {
- const input = (Array.isArray(data) ? data : [data]).map((seller) => {
+ const sellers = await this.sellerService_.update(
+ this.prepareSellerInput_(data),
+ sharedContext,
+ )
+ const result = await this.baseRepository_.serialize<SellerDTO[]>(sellers)
+ return (Array.isArray(data) ? result : result[0]) as any
+ }
+
+ protected prepareSellerInput_(data: unknown) {
+ const input = (Array.isArray(data) ? data : [data]) as SellerInput[]
+ return input.map((seller) => {
this.validateSellerData_(seller)
if (!seller.handle && seller.name) {
@@ -141,9 +167,6 @@ class SellerModuleService extends MedusaService({
return seller
})
-
- // @ts-ignore
- return super.updateSellers(input, sharedContext) as any
}
@InjectTransactionManager()
diff --git a/packages/core/src/with-mercur.ts b/packages/core/src/with-mercur.ts
index 51e74d9a1..55cd64651 100644
--- a/packages/core/src/with-mercur.ts
+++ b/packages/core/src/with-mercur.ts
@@ -1,7 +1,11 @@
import "./patches/register"
import type { InputConfigWithArrayModules } from "@medusajs/framework/types"
-import { defineConfig } from '@medusajs/framework/utils'
+import {
+ defineConfig,
+ MODULE_PACKAGE_NAMES,
+ Modules,
+} from '@medusajs/framework/utils'
import { assertPatchesDisabled } from "./patches"
import { disableMedusaMiddlewares } from "./utils/disable-medusa-middlewares"
@@ -48,9 +52,40 @@ export function withMercur(config: MercurInputConfig = {}): InputConfigWithArray
const featureFlags = {
...config.featureFlags,
+ index_engine: config.featureFlags?.index_engine ?? true,
+ caching: config.featureFlags?.caching ?? true,
}
- const modules = [...(config.modules ?? [])]
+ const redisUrl = config.projectConfig?.redisUrl
+
+ // The in-memory provider is per process, so multi-instance setups need Redis
+ // for invalidation to reach every instance. Without clones it hands out the
+ // cached objects themselves, and routes decorate rows (offers, prices).
+ const cachingModule = {
+ resolve: MODULE_PACKAGE_NAMES[Modules.CACHING],
+ options: redisUrl
+ ? {
+ providers: [
+ {
+ resolve: "@medusajs/medusa/caching-redis",
+ id: "caching-redis",
+ is_default: true,
+ options: { redisUrl, prefix: "mercur:" },
+ },
+ ],
+ }
+ : { in_memory: { enable: true, useClones: true } },
+ }
+
+ // Defaults go first: defineConfig keys modules by service name and the last
+ // entry wins, so any registration (or `disable`) in the project overrides them.
+ const modules = [
+ ...(featureFlags.index_engine
+ ? [{ resolve: MODULE_PACKAGE_NAMES[Modules.INDEX] }]
+ : []),
+ ...(featureFlags.caching ? [cachingModule] : []),
+ ...(config.modules ?? []),
+ ]
const plugins = [
...(config.plugins ?? []),
diff --git a/packages/core/src/workflows/cart/utils/seller-promotion-scope.ts b/packages/core/src/workflows/cart/utils/seller-promotion-scope.ts
index bf87d91ea..b880a5fd9 100644
--- a/packages/core/src/workflows/cart/utils/seller-promotion-scope.ts
+++ b/packages/core/src/workflows/cart/utils/seller-promotion-scope.ts
@@ -26,7 +26,14 @@ export const loadPromotionSellerIds = async (
fields: ["id", "seller.id"],
filters: { id: ids },
},
- { cache: { enable: true } }
+ {
+ cache: {
+ enable: true,
+ // Scoping a promotion to a seller only clears this link tag.
+ tags: ["LinkPromotionPromotionSellerSeller:list:*"],
+ computeAutomaticTags: true,
+ },
+ }
)
const result: PromotionSellerIds = {}