Skip to content
This repository has been archived by the owner on Dec 30, 2022. It is now read-only.

fix(indexUtils): avoid throw an error on cleanUp multi indices #1265

Merged
merged 2 commits into from
May 24, 2018
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
80 changes: 57 additions & 23 deletions packages/react-instantsearch/src/core/indexUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -187,30 +187,64 @@ export function getCurrentRefinementValue(
}

export function cleanUpValue(searchState, context, id) {
const index = getIndex(context);
const indexName = getIndex(context);
const { namespace, attributeName } = getNamespaceAndAttributeName(id);

if (hasMultipleIndex(context) && Boolean(searchState.indices)) {
return namespace
? {
...searchState,
indices: {
...searchState.indices,
[index]: {
...searchState.indices[index],
[namespace]: omit(
searchState.indices[index][namespace],
`${attributeName}`
),
},
},
}
: omit(searchState, `indices.${index}.${id}`);
} else {
return namespace
? {
...searchState,
[namespace]: omit(searchState[namespace], `${attributeName}`),
}
: omit(searchState, `${id}`);
return cleanUpValueWithMutliIndex({
attribute: attributeName,
searchState,
indexName,
id,
namespace,
});
}

return cleanUpValueWithSingleIndex({
attribute: attributeName,
searchState,
id,
namespace,
});
}

function cleanUpValueWithSingleIndex({
searchState,
id,
namespace,
attribute,
}) {
if (namespace) {
return {
...searchState,
[namespace]: omit(searchState[namespace], attribute),
};
}

return omit(searchState, id);
}

function cleanUpValueWithMutliIndex({
searchState,
indexName,
id,
namespace,
attribute,
}) {
const index = searchState.indices[indexName];

if (namespace && index) {
return {
...searchState,
indices: {
...searchState.indices,
[indexName]: {
...index,
[namespace]: omit(index[namespace], attribute),
},
},
};
}

return omit(searchState, `indices.${indexName}.${id}`);
}
23 changes: 23 additions & 0 deletions packages/react-instantsearch/src/core/indexUtils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,29 @@ describe('utility method for manipulating the search state', () => {
page: 1,
namespace: {},
});

// It might happen that we try to cleanUp an index that is not
// present on the searchState. We should not throw an error in
// that case, just return the searchState as it is.
searchState = {
page: 1,
indices: {
second: {
page: 1,
},
},
};

searchState = cleanUpValue(searchState, context, 'menu.category');

expect(searchState).toEqual({
page: 1,
indices: {
second: {
page: 1,
},
},
});
});

it('get results', () => {
Expand Down