4
0
forked from crowetic/commerce
commerce/framework/swell/product/use-search.tsx
ghoskin 4d85b43a30
Update Swell Provider (#359)
* fix update cart item

* update types

* update checkout

* update get-page, cleanup types

* revert change to incorrect file

* cleanup

Co-authored-by: Greg Hoskin <greghoskin@Gregs-MacBook-Pro.local>
2021-06-14 17:37:18 -03:00

60 lines
1.5 KiB
TypeScript

import { SWRHook } from '@commerce/utils/types'
import useSearch, { UseSearch } from '@commerce/product/use-search'
import { normalizeProduct } from '../utils'
import { SwellProduct } from '../types'
import type { SearchProductsHook } from '../types/product'
export default useSearch as UseSearch<typeof handler>
export type SearchProductsInput = {
search?: string
categoryId?: string
brandId?: string
sort?: string
}
export const handler: SWRHook<SearchProductsHook> = {
fetchOptions: {
query: 'products',
method: 'list',
},
async fetcher({ input, options, fetch }) {
const sortMap = new Map([
['latest-desc', ''],
['price-asc', 'price_asc'],
['price-desc', 'price_desc'],
['trending-desc', 'popularity'],
])
const { categoryId, search, sort = 'latest-desc' } = input
const mappedSort = sortMap.get(sort)
const { results, count: found } = await fetch({
query: 'products',
method: 'list',
variables: { category: categoryId, search, sort: mappedSort },
})
const products = results.map((product: SwellProduct) =>
normalizeProduct(product)
)
return {
products,
found,
}
},
useHook: ({ useData }) => (input = {}) => {
return useData({
input: [
['search', input.search],
['categoryId', input.categoryId],
['brandId', input.brandId],
['sort', input.sort],
],
swrOptions: {
revalidateOnFocus: false,
...input.swrOptions,
},
})
},
}