mirror of
https://github.com/vercel/commerce.git
synced 2025-07-22 20:26:49 +00:00
Add sorting to the API for search
This commit is contained in:
@@ -1,21 +1,39 @@
|
||||
import getAllProducts from '../../operations/get-all-products'
|
||||
import type { ProductsHandlers } from '../products'
|
||||
|
||||
const SORT: { [key: string]: string | undefined } = {
|
||||
latest: 'date_modified',
|
||||
trending: 'total_sold',
|
||||
price: 'price',
|
||||
}
|
||||
|
||||
// Return current cart info
|
||||
const getProducts: ProductsHandlers['getProducts'] = async ({
|
||||
res,
|
||||
body: { search, category, brand },
|
||||
body: { search, category, brand, sort },
|
||||
config,
|
||||
}) => {
|
||||
// Use a dummy base as we only care about the relative path
|
||||
const url = new URL('/v3/catalog/products', 'http://a')
|
||||
|
||||
if (search) url.searchParams.set('keyword', search)
|
||||
|
||||
if (category && Number.isInteger(Number(category)))
|
||||
url.searchParams.set('categories:in', category)
|
||||
|
||||
if (brand && Number.isInteger(Number(brand)))
|
||||
url.searchParams.set('brand_id', brand)
|
||||
|
||||
if (sort) {
|
||||
const [_sort, direction] = sort.split('-')
|
||||
const sortValue = SORT[_sort]
|
||||
|
||||
if (sortValue && direction) {
|
||||
url.searchParams.set('sort', sortValue)
|
||||
url.searchParams.set('direction', direction)
|
||||
}
|
||||
}
|
||||
|
||||
// We only want the id of each product
|
||||
url.searchParams.set('include_fields', 'id')
|
||||
|
||||
|
@@ -15,7 +15,7 @@ export type SearchProductsData = {
|
||||
export type ProductsHandlers = {
|
||||
getProducts: BigcommerceHandler<
|
||||
SearchProductsData,
|
||||
{ search?: 'string'; category?: string; brand?: string }
|
||||
{ search?: 'string'; category?: string; brand?: string; sort?: string }
|
||||
>
|
||||
}
|
||||
|
||||
|
Reference in New Issue
Block a user