From 379e68685a31404f8483e40e74c883d7bcc6715f Mon Sep 17 00:00:00 2001 From: almostSouji Date: Tue, 22 Oct 2024 07:55:42 +0200 Subject: [PATCH] fix(algolia): improve resilience to unexpected data shape * filter compact id > 100 * be less harsh with most specific hierarchy dedupes * filter hierarchy earlier to handle lvl0/lvl1 null values * allow 100 length in name string to match api restriction --- .../autocomplete/algoliaAutoComplete.ts | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/functions/autocomplete/algoliaAutoComplete.ts b/src/functions/autocomplete/algoliaAutoComplete.ts index dc7933f..def422e 100644 --- a/src/functions/autocomplete/algoliaAutoComplete.ts +++ b/src/functions/autocomplete/algoliaAutoComplete.ts @@ -28,7 +28,9 @@ function headingIsSimilar(one: string, other: string) { export function resolveHitToNamestring(hit: AlgoliaHit) { const { hierarchy } = hit; - const [lvl0, lvl1, ...restLevels] = Object.values(hierarchy).map((heading) => removeDtypesPrefix(heading)); + const [lvl0, lvl1, ...restLevels] = Object.values(hierarchy) + .filter(Boolean) + .map((heading) => removeDtypesPrefix(heading)); const headingParts = []; @@ -38,8 +40,8 @@ export function resolveHitToNamestring(hit: AlgoliaHit) { headingParts.push(`${lvl0}:`, lvl1); } - const mostSpecific = restLevels.filter(Boolean).at(-1); - if (mostSpecific?.length && !headingIsSimilar(lvl0, mostSpecific) && !headingIsSimilar(lvl1, mostSpecific)) { + const mostSpecific = restLevels.at(-1); + if (mostSpecific?.length && mostSpecific !== lvl0 && mostSpecific !== lvl1) { headingParts.push(`- ${mostSpecific}`); } @@ -48,10 +50,16 @@ export function resolveHitToNamestring(hit: AlgoliaHit) { function autoCompleteMap(elements: AlgoliaHit[]) { const uniqueElements = elements.filter(dedupeAlgoliaHits()); - return uniqueElements.map((element) => ({ - name: truncate(resolveHitToNamestring(element), 90, ''), - value: compactAlgoliaObjectId(element.objectID), - })); + return uniqueElements + .filter((element) => { + const value = compactAlgoliaObjectId(element.objectID); + // API restriction. Cannot resolve from truncated, so filtering here. + return value.length <= 100; + }) + .map((element) => ({ + name: truncate(resolveHitToNamestring(element), 100, ''), + value: compactAlgoliaObjectId(element.objectID), + })); } export async function algoliaAutoComplete(