From 10cdd2c77ebc464a58507227a2f1f5462cd80161 Mon Sep 17 00:00:00 2001 From: Paul Chavard Date: Wed, 16 Jun 2021 09:28:07 +0200 Subject: [PATCH] Apply suggestions from code review Co-authored-by: Pierre de La Morinerie --- app/javascript/components/ComboCommunesSearch.jsx | 12 ++++++++++-- app/javascript/components/shared/queryClient.js | 8 ++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/app/javascript/components/ComboCommunesSearch.jsx b/app/javascript/components/ComboCommunesSearch.jsx index 81d9e1d9d..5216bae03 100644 --- a/app/javascript/components/ComboCommunesSearch.jsx +++ b/app/javascript/components/ComboCommunesSearch.jsx @@ -3,16 +3,24 @@ import { QueryClientProvider } from 'react-query'; import { matchSorter } from 'match-sorter'; import ComboSearch from './ComboSearch'; -import { queryClient } from './shared/queryClient'; +import { queryClient, searchResultsLimit } from './shared/queryClient'; function expandResultsWithMultiplePostalCodes(term, results) { + // A single result may have several associated postal codes. + // To make the search results more precise, we want to generate + // an actual result for each postal code. const expandedResults = results.flatMap((result) => result.codesPostaux.map((codePostal) => ({ ...result, codesPostaux: [codePostal] })) ); - const limit = term.length > 5 ? 10 : 5; + + // Some very large cities (like Paris) have A LOT of associated postal codes. + // As we generated one result per postal code, we now have a lot of results + // for the same city. If the number of results is above the threshold, we use + // local search to narrow the results. + const limit = searchResultsLimit(term); if (expandedResults.length > limit) { return matchSorter(expandedResults, term, { keys: [(item) => `${item.nom} (${item.codesPostaux[0]})`, 'code'], diff --git a/app/javascript/components/shared/queryClient.js b/app/javascript/components/shared/queryClient.js index a39b37fc9..b651dc22a 100644 --- a/app/javascript/components/shared/queryClient.js +++ b/app/javascript/components/shared/queryClient.js @@ -13,6 +13,11 @@ export const queryClient = new QueryClient({ } }); +// Avoid hiding similar matches for precise queries (like "Sainte Marie") +export function searchResultsLimit(term) { + return term.length > 5 ? 10 : 5; +} + function buildURL(scope, term) { term = encodeURIComponent(term.replace(/\(|\)/g, '')); if (scope === 'adresse') { @@ -23,8 +28,7 @@ function buildURL(scope, term) { if (isNumeric(term)) { return `${api_geo_url}/communes?codePostal=${term}&limit=5`; } - // Avoid hiding similar matches for precise queries (like "Sainte Marie") - const limit = term.length > 5 ? 10 : 5; + const limit = searchResultsLimit(term); return `${api_geo_url}/communes?nom=${term}&boost=population&limit=${limit}`; } else if (isNumeric(term)) { const code = term.padStart(2, '0');