55 AlgoliaSearchResponse ,
66 AlgoliaMultipleQueriesQuery ,
77 SearchContext ,
8+ FacetDistribution ,
89} from '../types'
910import {
1011 adaptSearchResponse ,
@@ -28,11 +29,6 @@ export function instantMeiliSearch(
2829 apiKey = '' ,
2930 instantMeiliSearchOptions : InstantMeiliSearchOptions = { }
3031) : InstantMeiliSearchInstance {
31- const searchCache = SearchCache ( )
32- // create search resolver with included cache
33- const searchResolver = SearchResolver ( searchCache )
34- // paginationTotalHits can be 0 as it is a valid number
35- let defaultFacetDistribution : any = { }
3632 const clientAgents = constructClientAgents (
3733 instantMeiliSearchOptions . clientAgents
3834 )
@@ -43,6 +39,12 @@ export function instantMeiliSearch(
4339 clientAgents,
4440 } )
4541
42+ const searchCache = SearchCache ( )
43+ // create search resolver with included cache
44+ const searchResolver = SearchResolver ( meilisearchClient , searchCache )
45+
46+ let defaultFacetDistribution : FacetDistribution
47+
4648 return {
4749 clearCache : ( ) => searchCache . clearCache ( ) ,
4850 /**
@@ -63,26 +65,29 @@ export function instantMeiliSearch(
6365 // Adapt search request to Meilisearch compliant search request
6466 const adaptedSearchRequest = adaptSearchParams ( searchContext )
6567
66- // Search response from Meilisearch
67- const searchResponse = await searchResolver . searchResponse (
68- searchContext ,
69- adaptedSearchRequest ,
70- meilisearchClient
71- )
72-
7368 // Cache first facets distribution of the instantMeilisearch instance
7469 // Needed to add in the facetDistribution the fields that were not returned
7570 // When the user sets `keepZeroFacets` to true.
76- defaultFacetDistribution = cacheFirstFacetDistribution (
77- defaultFacetDistribution ,
78- searchResponse
71+ if ( defaultFacetDistribution === undefined ) {
72+ defaultFacetDistribution = await cacheFirstFacetDistribution (
73+ searchResolver ,
74+ searchContext
75+ )
76+ searchContext . defaultFacetDistribution = defaultFacetDistribution
77+ }
78+
79+ // Search response from Meilisearch
80+ const searchResponse = await searchResolver . searchResponse (
81+ searchContext ,
82+ adaptedSearchRequest
7983 )
8084
8185 // Adapt the Meilisearch responsne to a compliant instantsearch.js response
8286 const adaptedSearchResponse = adaptSearchResponse < T > (
8387 searchResponse ,
8488 searchContext
8589 )
90+
8691 return adaptedSearchResponse
8792 } catch ( e : any ) {
8893 console . error ( e )
0 commit comments