Updated sorting logic

This commit is contained in:
Luis Alvarez
2020-10-14 12:47:22 -05:00
parent cdb2cbdebd
commit 32da7ddcc1
4 changed files with 79 additions and 49 deletions

View File

@@ -1,4 +1,7 @@
import getAllProducts from '../../operations/get-all-products'
import getAllProducts, {
Products,
Product,
} from '../../operations/get-all-products'
import type { ProductsHandlers } from '../products'
const SORT: { [key: string]: string | undefined } = {
@@ -16,6 +19,9 @@ const getProducts: ProductsHandlers['getProducts'] = async ({
// Use a dummy base as we only care about the relative path
const url = new URL('/v3/catalog/products', 'http://a')
// The limit should math the number of products returned by `getAllProducts`
url.searchParams.set('limit', '10')
if (search) url.searchParams.set('keyword', search)
if (category && Number.isInteger(Number(category)))
@@ -35,7 +41,7 @@ const getProducts: ProductsHandlers['getProducts'] = async ({
}
// We only want the id of each product
url.searchParams.set('include_fields', 'id')
url.searchParams.set('include_fields', 'id,price')
const { data } = await config.storeApiFetch<{ data: { id: number }[] }>(
url.pathname + url.search
@@ -43,7 +49,23 @@ const getProducts: ProductsHandlers['getProducts'] = async ({
const entityIds = data.map((p) => p.id)
const found = entityIds.length > 0
// We want the GraphQL version of each product
const { products } = await getAllProducts({ variables: { entityIds } })
const graphqlData = await getAllProducts({ variables: { entityIds } })
// Put the products in an object that we can use to get them by id
const productsById = graphqlData.products.reduce<{ [k: number]: Product }>(
(prods, p) => {
prods[p.node.entityId] = p
return prods
},
{}
)
const products: Products = []
// Populate the products array with the graphql products, in the order
// assigned by the list of entity ids
entityIds.forEach((id) => {
const product = productsById[id]
if (product) products.push(product)
})
res.status(200).json({ data: { products, found } })
}