Skip to content

Commit

Permalink
fix(highlight): highlight should work even if the attribute is missing (
Browse files Browse the repository at this point in the history
#1791)

Since algolia does not enforce a schema on the records, it is possible
that an highlighted value is only available on some of them. This means
that react-instantsearch should not throw when highlighting an attribute
that is missing from the hit.

fix #1790
  • Loading branch information
bobylito authored and mthuret committed Jan 3, 2017
1 parent ad2ded3 commit 5b79b15
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 13 deletions.
7 changes: 3 additions & 4 deletions packages/react-instantsearch/src/core/highlight.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,10 @@ export default function parseAlgoliaHit({
}) {
if (!hit) throw new Error('`hit`, the matching record, must be provided');

const highlightedValue = get(hit._highlightResult, attributeName);
if (!highlightedValue) throw new Error(
`\`attributeName\`=${attributeName} must resolve to an highlighted attribute in the record`);
const highlightObject = get(hit._highlightResult, attributeName);
const highlightedValue = !highlightObject ? '' : highlightObject.value;

return parseHighlightedAttribute({preTag, postTag, highlightedValue: highlightedValue.value});
return parseHighlightedAttribute({preTag, postTag, highlightedValue});
}

/**
Expand Down
15 changes: 6 additions & 9 deletions packages/react-instantsearch/src/core/highlight.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@
import parseAlgoliaHit from './highlight.js';

describe('parseAlgoliaHit()', () => {
it('it does not break when there is a missing attribute', () => {
const attributeName = 'attr';
const out = parseAlgoliaHit({attributeName, hit: {}});
expect(out).toEqual([]);
});

it('creates a single element when there is no tag', () => {
const value = 'foo bar baz';
const attributeName = 'attr';
Expand Down Expand Up @@ -61,15 +67,6 @@ describe('parseAlgoliaHit()', () => {
]);
});

it('throws when the attribute is not highlighted in the hit', () => {
expect(parseAlgoliaHit.bind(null, {
attributeName: 'notHighlightedAttribute',
hit: {notHighlightedAttribute: 'some value'},
})).toThrowError(
'`attributeName`=notHighlightedAttribute must resolve to an highlighted attribute in the record'
);
});

it('throws when hit is `null`', () => {
expect(parseAlgoliaHit.bind(null, {
attributeName: 'unknownattribute',
Expand Down

0 comments on commit 5b79b15

Please sign in to comment.