Skip to content
This repository has been archived by the owner on Jul 11, 2023. It is now read-only.

fix(getFacetValues): don't throw error when there's no facet #720

Merged
merged 2 commits into from
Jul 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1155,7 +1155,7 @@ declare namespace algoliasearchHelper {
getFacetValues(
attribute: string,
opts: any
): SearchResults.FacetValue[] | SearchResults.HierarchicalFacet;
): SearchResults.FacetValue[] | SearchResults.HierarchicalFacet | undefined;

/**
* Returns the facet stats if attribute is defined and the facet contains some.
Expand Down
6 changes: 4 additions & 2 deletions src/SearchResults/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -674,7 +674,7 @@ function vanillaSortFn(order, data) {
* bigger or -1 otherwise.
*
* The default value for this attribute `['isRefined:desc', 'count:desc', 'name:asc']`
* @return {FacetValue[]|HierarchicalFacet} depending on the type of facet of
* @return {FacetValue[]|HierarchicalFacet|undefined} depending on the type of facet of
* the attribute requested (hierarchical, disjunctive or conjunctive)
* @example
* helper.on('result', function(event){
Expand All @@ -693,7 +693,9 @@ function vanillaSortFn(order, data) {
*/
SearchResults.prototype.getFacetValues = function(attribute, opts) {
var facetValues = extractNormalizedFacetValues(this, attribute);
if (!facetValues) throw new Error(attribute + ' is not a retrieved facet.');
if (!facetValues) {
return undefined;
}

var options = defaultsPure({}, opts, {sortBy: SearchResults.DEFAULT_SORT});

Expand Down
17 changes: 17 additions & 0 deletions test/spec/SearchResults/getFacetValues.js
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,20 @@ test('getFacetValues(disjunctive) returns correct facet values with the name `le
expect(facetValues).toEqual(expected);
expect(facetValues.length).toBe(2);
});

test('getFacetValues(unknown) returns undefined (does not throw)', function() {
var searchParams = new SearchParameters({
index: 'instant_search'
});

var result = {
query: '',
// it does not matter if the result here is given or not,
// if something is not a parameter, it will not be read.
facets: {}
};

var results = new SearchResults(searchParams, [result, result]);

expect(results.getFacetValues('type')).toBeUndefined();
});