Skip to content

Commit

Permalink
feat(index): merge ruleContexts search parameter
Browse files Browse the repository at this point in the history
  • Loading branch information
francoischalifour committed Jul 12, 2019
1 parent 37cff4b commit 4b3e6cb
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
27 changes: 27 additions & 0 deletions src/lib/utils/__tests__/mergeSearchParameters-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,4 +367,31 @@ describe('mergeSearchParameters', () => {
})
);
});

it('merges and dedupes `ruleContexts` parameters', () => {
const actual = merge(
algoliasearchHelper.SearchParameters.make({
ruleContexts: ['ais-genre-comedy'],
}),
algoliasearchHelper.SearchParameters.make({
ruleContexts: ['ais-genre-thriller', 'ais-genre-comedy'],
}),
algoliasearchHelper.SearchParameters.make({
ruleContexts: ['ais-rating-4'],
}),
algoliasearchHelper.SearchParameters.make({
ruleContexts: [],
})
);

expect(actual).toEqual(
algoliasearchHelper.SearchParameters.make({
ruleContexts: [
'ais-genre-comedy',
'ais-genre-thriller',
'ais-rating-4',
],
})
);
});
});
25 changes: 24 additions & 1 deletion src/lib/utils/mergeSearchParameters.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { SearchParameters } from '../../types';
import findIndex from './findIndex';
import uniq from './uniq';

type Merger = (
left: SearchParameters,
Expand All @@ -17,6 +18,7 @@ const mergeWithRest: Merger = (left, right) => {
tagRefinements,
hierarchicalFacets,
hierarchicalFacetsRefinements,
ruleContexts,
...rest
} = right;

Expand Down Expand Up @@ -103,6 +105,23 @@ const mergeHierarchicalFacetsRefinements: Merger = (left, right) =>
},
});

const mergeRuleContexts: Merger = (left, right) => {
const ruleContexts: string[] = uniq(
([] as any)
.concat(left.ruleContexts)
.concat(right.ruleContexts)
.filter(Boolean)
);

if (ruleContexts.length > 0) {
return left.setQueryParameters({
ruleContexts,
});
}

return left;
};

const merge = (...parameters: SearchParameters[]): SearchParameters =>
parameters.reduce((left, right) => {
const hierarchicalFacetsRefinementsMerged = mergeHierarchicalFacetsRefinements(
Expand Down Expand Up @@ -137,7 +156,11 @@ const merge = (...parameters: SearchParameters[]): SearchParameters =>
facetRefinementsMerged,
right
);
const facetsMerged = mergeFacets(disjunctiveFacetsMerged, right);
const ruleContextsMerged = mergeRuleContexts(
disjunctiveFacetsMerged,
right
);
const facetsMerged = mergeFacets(ruleContextsMerged, right);

return mergeWithRest(facetsMerged, right);
});
Expand Down

0 comments on commit 4b3e6cb

Please sign in to comment.