import { memoize } from 'lodash' ; import { CoreSetup } from 'src/core/public' ; import { IIndexPattern , IFieldType , UI_SETTINGS } from '../../../common' ; function resolver ( title , field , query , boolFilter ) { const ttl = Math . floor ( Date . now ( ) / 1000 / 60 ) ; return [ ttl , query , title , field . name , JSON . stringify ( boolFilter ) ] . join ( '|' ) ; } export type ValueSuggestionsGetFn = ( args : ValueSuggestionsGetFnArgs ) => Promise < any [ ] > ; interface ValueSuggestionsGetFnArgs { indexPattern : IIndexPattern ; field : IFieldType ; query : string ; boolFilter ? : any [ ] ; signal ? : AbortSignal ; } export const getEmptyValueSuggestions = ( ( ) => Promise . resolve ( [ ] ) ) as ValueSuggestionsGetFn ; export const setupValueSuggestionProvider = ( core ) : ValueSuggestionsGetFn => { const requestSuggestions = memoize ( ( index , field , query , boolFilter = [ ] , signal ? ) => core . http . fetch ( `/api/opensearch-dashboards/suggestions/values/${ index }` , { method : 'POST' , body : JSON . stringify ( { query , field : field . name , boolFilter } ) , signal , } ) , resolver ) ; return async ( { indexPattern , field , query , boolFilter , signal , } ) : Promise < any [ ] > => { const shouldSuggestValues = core ! . uiSettings . get < boolean > ( UI_SETTINGS . FILTERS_EDITOR_SUGGEST_VALUES ) ; const { title } = indexPattern ; if ( field . type === 'boolean' ) { return [ true , false ] ; } else if ( ! shouldSuggestValues || ! field . aggregatable || field . type !== 'string' ) { return [ ] ; } return await requestSuggestions ( title , field , query , boolFilter , signal ) ; } ; } ;