Skip to content

Commit 6308b63

Browse files
committed
Refactor: create buildHits function
1 parent 2701af3 commit 6308b63

File tree

1 file changed

+29
-22
lines changed

1 file changed

+29
-22
lines changed

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

Lines changed: 29 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -46,28 +46,7 @@ export function fetchMeilisearchResults<TRecord = Record<string, any>>({
4646
const query = queries[resultsArrayIndex]
4747
return {
4848
...result,
49-
hits: result.hits.map((hit) => ({
50-
...hit,
51-
_highlightResult: (
52-
Object.entries(hit?._highlightResult || {}) as Array<
53-
| [keyof TRecord, { value: string }]
54-
| [keyof TRecord, Array<{ value: string }>] // if the field is an array
55-
>
56-
).reduce((acc, [field, highlightResult]) => {
57-
return {
58-
...acc,
59-
// if the field is an array, highlightResult is an array of objects
60-
[field]: mapOneOrMany(highlightResult, (highlightResult) =>
61-
calculateHighlightMetadata(
62-
query.query || '',
63-
query.params?.highlightPreTag || HIGHLIGHT_PRE_TAG,
64-
query.params?.highlightPostTag || HIGHLIGHT_POST_TAG,
65-
highlightResult.value
66-
)
67-
),
68-
}
69-
}, {} as HighlightResult<TRecord>),
70-
})),
49+
hits: buildHits<TRecord>(result, query),
7150
}
7251
}
7352
)
@@ -89,3 +68,31 @@ function buildSearchRequest(queries: AlgoliaMultipleQueriesQuery[]) {
8968
}
9069
})
9170
}
71+
72+
function buildHits<TRecord>(
73+
result: AlgoliaSearchResponse<TRecord>,
74+
query: AlgoliaMultipleQueriesQuery
75+
) {
76+
return result.hits.map((hit) => ({
77+
...hit,
78+
_highlightResult: (
79+
Object.entries(hit?._highlightResult || {}) as Array<
80+
| [keyof TRecord, { value: string }]
81+
| [keyof TRecord, Array<{ value: string }>] // if the field is an array
82+
>
83+
).reduce((acc, [field, highlightResult]) => {
84+
return {
85+
...acc,
86+
// if the field is an array, highlightResult is an array of objects
87+
[field]: mapOneOrMany(highlightResult, (highlightResult) =>
88+
calculateHighlightMetadata(
89+
query.query || '',
90+
query.params?.highlightPreTag || HIGHLIGHT_PRE_TAG,
91+
query.params?.highlightPostTag || HIGHLIGHT_POST_TAG,
92+
highlightResult.value
93+
)
94+
),
95+
}
96+
}, {} as HighlightResult<TRecord>),
97+
}))
98+
}

0 commit comments

Comments
 (0)