import { useEffect , useState } from 'react' ; import { IUiSettingsClient } from 'kibana/public' ; import { i18n } from '@kbn/i18n' ; import { getDataViewById , getDataViewAndSavedSearch , DataViewAndSavedSearch , } from '../util/index_utils' ; import { createSearchItems } from '../jobs/new_job/utils/new_job_utils' ; import { ResolverResults , Resolvers } from './resolvers' ; import { MlContextValue } from '../contexts/ml' ; import { useNotifications } from '../contexts/kibana' ; import { useCreateAndNavigateToMlLink } from '../contexts/kibana/use_create_url' ; import { ML_PAGES } from '../../../common/constants/locator' ; import type { DataViewsContract } from '../../../../../../src/plugins/data_views/public' ; param dataViewId param savedSearchId param config param resolvers return { context export const useResolver = ( dataViewId , savedSearchId , config , dataViewsContract , resolvers ) : { context : MlContextValue ; results : ResolverResults ; } => { const notifications = useNotifications ( ) ; const funcNames = Object . keys ( resolvers ) ; const funcs = Object . values ( resolvers ) ; const tempResults = funcNames . reduce ( ( p , c ) => { p [ c ] = { } ; return p ; } , { } as ResolverResults ) ; const [ context , setContext ] = useState < any | null > ( null ) ; const [ results , setResults ] = useState ( tempResults ) ; const redirectToJobsManagementPage = useCreateAndNavigateToMlLink ( ML_PAGES . ANOMALY_DETECTION_JOBS_MANAGE ) ; useEffect ( ( ) => { ( async ( ) => { try { const res = await Promise . all ( funcs . map ( ( r ) => r ( ) ) ) ; res . forEach ( ( r , i ) => ( tempResults [ funcNames [ i ] ] = r ) ) ; setResults ( tempResults ) ; } catch ( error ) { return ; } try { if ( dataViewId === '' ) { throw new Error ( i18n . translate ( 'xpack.ml.useResolver.errorIndexPatternIdEmptyString' , { defaultMessage : 'dataViewId must not be empty string.' , } ) ) ; } let dataViewAndSavedSearch = { savedSearch : null , dataView : null , } ; if ( savedSearchId !== undefined ) { dataViewAndSavedSearch = await getDataViewAndSavedSearch ( savedSearchId ) ; } else if ( dataViewId !== undefined ) { dataViewAndSavedSearch . dataView = await getDataViewById ( dataViewId ) ; } const { savedSearch , dataView } = dataViewAndSavedSearch ; const { combinedQuery } = createSearchItems ( config , dataView !== null ? dataView : undefined , savedSearch ) ; setContext ( { combinedQuery , currentDataView : dataView , currentSavedSearch : savedSearch , dataViewsContract , kibanaConfig : config , } ) ; } catch ( error ) { notifications . toasts . addError ( new Error ( error ) , { title : i18n . translate ( 'xpack.ml.useResolver.errorTitle' , { defaultMessage : 'An error has occurred' , } ) , } ) ; await redirectToJobsManagementPage ( ) ; } } ) ( ) ; } , [ ] ) ; return { context , results } ; } ;