Skip to content

Commit db9b5b8

Browse files
jezzzmStrift
authored andcommitted
fix: defensive check for existence of value key
1 parent efdc741 commit db9b5b8

File tree

1 file changed

+37
-9
lines changed

1 file changed

+37
-9
lines changed

packages/autocomplete-client/src/search/fetchMeilisearchResults.ts

Lines changed: 37 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -64,22 +64,27 @@ export function fetchMeilisearchResults<TRecord = Record<string, any>>({
6464
...hit,
6565
_highlightResult: (
6666
Object.entries(hit?._highlightResult || {}) as Array<
67-
| [keyof TRecord, { value: string }]
68-
| [keyof TRecord, Array<{ value: string }>] // if the field is an array
67+
[keyof TRecord, PossibleHighlightResult]
6968
>
7069
).reduce((acc, [field, highlightResult]) => {
71-
return {
72-
...acc,
73-
// if the field is an array, highlightResult is an array of objects
74-
[field]: mapOneOrMany(highlightResult, (highlightResult) =>
75-
calculateHighlightMetadata(
70+
if (!isDefinedHighlightValue(highlightResult)) {
71+
return acc
72+
}
73+
74+
// if the field is an array, highlightResult is an array of objects
75+
acc[field] = mapOneOrMany(
76+
highlightResult,
77+
(highlightResult) => {
78+
return calculateHighlightMetadata(
7679
query.query || '',
7780
query.params?.highlightPreTag || HIGHLIGHT_PRE_TAG,
7881
query.params?.highlightPostTag || HIGHLIGHT_POST_TAG,
7982
highlightResult.value
8083
)
81-
),
82-
}
84+
}
85+
)
86+
87+
return acc
8388
}, {} as HighlightResult<TRecord>),
8489
})),
8590
}
@@ -144,3 +149,26 @@ function calculateHighlightMetadata(
144149
function mapOneOrMany<T, U>(value: T | T[], mapFn: (value: T) => U): U | U[] {
145150
return Array.isArray(value) ? value.map(mapFn) : mapFn(value)
146151
}
152+
153+
type DefinedHighlightResult = { value: string } | Array<{ value: string }> // if the field is an array
154+
155+
/**
156+
* Some fields may not return a value at all - nested arrays/objects for example
157+
*
158+
* Ideally server honours the `attributesToHighlight` param and only includes
159+
* those attributes in the response rather than all attributes (highlighted or
160+
* not)
161+
*/
162+
type UndefinedHighlightResult = { value?: never } | Array<{ value?: never }>
163+
164+
type PossibleHighlightResult = DefinedHighlightResult | UndefinedHighlightResult
165+
166+
function isDefinedHighlightValue(
167+
input: PossibleHighlightResult
168+
): input is DefinedHighlightResult {
169+
if (Array.isArray(input)) {
170+
return input.every((r) => r.value !== undefined)
171+
}
172+
173+
return input.value !== undefined
174+
}

0 commit comments

Comments
 (0)