fix: Ensure passed Id filters get applied on top of maybe link filter (#7182)

This commit is contained in:
Stevche Radevski
2024-05-01 11:25:24 +02:00
committed by GitHub
parent 3bf6e50744
commit d930d88369
5 changed files with 62 additions and 1 deletions

View File

@@ -247,6 +247,18 @@ medusaIntegrationTestRunner({
])
})
it("should list products by id", async () => {
let response = await api.get(`/store/products?id[]=${product.id}`)
expect(response.status).toEqual(200)
expect(response.data.count).toEqual(1)
expect(response.data.products).toEqual([
expect.objectContaining({
id: product.id,
}),
])
})
it("should throw error when publishable key is invalid", async () => {
let error = await api
.get(`/store/products?sales_channel_id[]=does-not-exist`, {

View File

@@ -1,6 +1,7 @@
import {
ContainerRegistrationKeys,
remoteQueryObjectFromString,
arrayIntersection,
} from "@medusajs/utils"
import { NextFunction } from "express"
import { MedusaRequest } from "../../types/routing"
@@ -37,7 +38,19 @@ export function maybeApplyLinkFilter({
const resources = await remoteQuery(queryObject)
filterableFields.id = resources.map((p) => p[resourceId])
let existingIdFilters = filterableFields.id as string[] | string | undefined
if (existingIdFilters) {
if (typeof existingIdFilters === "string") {
existingIdFilters = [existingIdFilters]
}
filterableFields.id = arrayIntersection(
existingIdFilters,
resources.map((p) => p[resourceId])
)
} else {
filterableFields.id = resources.map((p) => p[resourceId])
}
return next()
}

View File

@@ -0,0 +1,18 @@
import { arrayIntersection } from "../array-intersection"
describe("arrayIntersection", function () {
it("should return the intersection between two arrays", function () {
const output = arrayIntersection(["foo", "bar"], ["bar", "baz"])
expect(output).toEqual(["bar"])
})
it("should return an empty array if there is no intersection", function () {
const output = arrayIntersection(["bar", "baz"], ["foo", "boo"])
expect(output).toEqual([])
})
it("should return an all items when the arrays are equivalent", function () {
const output = arrayIntersection(["bar", "baz"], ["baz", "bar"])
expect(output).toEqual(["baz", "bar"])
})
})

View File

@@ -0,0 +1,17 @@
type ArrayIntersectionElement = string | number
export function arrayIntersection<TElement = ArrayIntersectionElement>(
firstArray: TElement[],
secondArray: TElement[]
): TElement[] {
const firstArraySet = new Set(firstArray)
const res = new Set<TElement>()
secondArray.forEach((element) => {
if (firstArraySet.has(element)) {
res.add(element)
}
})
return Array.from(res)
}

View File

@@ -1,5 +1,6 @@
export * from "./alter-columns-helper"
export * from "./array-difference"
export * from "./array-intersection"
export * from "./build-query"
export * from "./camel-to-snake-case"
export * from "./container"