Add sorting to the API for search

This commit is contained in:
Luis Alvarez 2020-10-14 10:53:03 -05:00
parent 9a98c01a92
commit 398feac176
3 changed files with 21 additions and 2 deletions

View File

@ -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')

View File

@ -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 }
>
}

View File

@ -114,6 +114,7 @@ export default function Home({
/>
</>
) : (
// TODO: add a proper loading state
<div>Searching...</div>
)}
</div>