Skip to content

Commit

Permalink
fix: don't require searchable facets for popular categories (#31)
Browse files Browse the repository at this point in the history
The `getAlgoliaFacets` function requires the targeted facet to be searchable.
Since it's not a requirement for our SFRA cartridge, if people try the
demo on their existing index, they would get the following error and the
search results wouldn't appear:
```
"Cannot search in __primary_category.1 attribute, you need to add searchable(__primary_category.1) to attributesForFaceting."
```

Algolia has a way to get the facets and their count that doesn't require
to have searchable facets:
https://www.algolia.com/doc/guides/managing-results/refine-results/faceting/#retrieving-facets
This PR uses this method to retrieve the facets.

The `results` object contains the following object:
```json
[{
  "facets": {
    "__primary_category.1": {
      "Mens > Clothing": 490,
      "Womens > Accessories": 91,
      // ...
    }
  },
  // ...
}]
```

The `transformResponse` function transforms it into a sorted array of
`{ label: int, count: int }` objects, like the `getAlgoliaFacets` was doing.

---
SFCC-388
  • Loading branch information
sbellone authored Oct 14, 2024
1 parent 5b6d7ef commit 0debc6d
Showing 1 changed file with 21 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/** @jsxRuntime classic */
/** @jsx React.createElement */

import {getAlgoliaFacets} from '@algolia/autocomplete-js'
import {getAlgoliaResults} from '@algolia/autocomplete-js'
import React, {createElement, Fragment} from 'react'
import {ALGOLIA_PRODUCTS_INDEX_NAME} from '../constants'
import {searchClient} from '../searchClient'
Expand Down Expand Up @@ -39,18 +39,33 @@ export const popularCategoriesPlugin = (navigate) => ({
{
sourceId: 'popularCategoriesPlugin',
getItems() {
return getAlgoliaFacets({
return getAlgoliaResults({
searchClient,
queries: [
{
indexName: ALGOLIA_PRODUCTS_INDEX_NAME,
facet: '__primary_category.1',
query: '',
params: {
facetQuery: '',
maxFacetHits: 4
facets: ['__primary_category.1'],
hitsPerPage: 1,
}
}
]
],
transformResponse({ results }) {
const categoryFacets = results[0].facets['__primary_category.1'];
if (!categoryFacets) {
return [];
}
const res = [];
for (let [key, value] of Object.entries(categoryFacets)) {
res.push({ label: key, count: value });
}
// Sort category facets by their count and return only the first 4
res.sort((a, b) => {
return b.count - a.count;
});
return [res.slice(0, 4)];
},
})
},
onSelect({setIsOpen}) {
Expand Down

0 comments on commit 0debc6d

Please sign in to comment.