refactor category and brand filtering logic

Signed-off-by: Loan Laux <loan@outgrow.io>
This commit is contained in:
Loan Laux
2021-07-07 19:16:45 +03:00
parent 2160264d60
commit c2c43b76aa
8 changed files with 42 additions and 29 deletions

View File

@@ -3,34 +3,31 @@ import useSearch, { UseSearch } from '@commerce/product/use-search'
export default useSearch as UseSearch<typeof handler>
export type SearchProductsInput = {
search?: string
categoryId?: number | string
brandId?: number
sort?: string
locale?: string
}
export const handler: SWRHook<any> = {
fetchOptions: {
url: '/api/catalog/products',
method: 'GET',
},
fetcher({ input: { search, categoryId, brandId, sort }, options, fetch }) {
async fetcher({ input: { search, categoryId, brandId, sort }, options, fetch }) {
// Use a dummy base as we only care about the relative path
const url = new URL(options.url!, 'http://a')
if (search) url.searchParams.set('search', search)
if (Number.isInteger(categoryId))
if (categoryId)
url.searchParams.set('categoryId', String(categoryId))
if (Number.isInteger(brandId))
if (brandId)
url.searchParams.set('brandId', String(brandId))
if (sort) url.searchParams.set('sort', sort)
return fetch({
const results = await fetch({
url: url.pathname + url.search,
method: options.method,
})
return {
products: results?.products ?? [],
found: results?.products?.length > 0 ?? false,
}
},
useHook:
({ useData }) =>