import { useCallback , useState } from 'react' ; import { ToastsStart } from 'kibana/public' ; import { IHttpFetchError , ResponseErrorBody , CoreStart } from 'kibana/public' ; import { i18n } from '@kbn/i18n' ; import { ExploreRequest , GraphExploreCallback , GraphSearchCallback , SearchRequest } from '../types' ; import { formatHttpError } from './format_http_error' ; interface UseGraphLoaderProps { toastNotifications : ToastsStart ; coreStart : CoreStart ; } export const useGraphLoader = ( { toastNotifications , coreStart } ) => { const [ loading , setLoading ] = useState ( false ) ; const handleHttpError = useCallback ( ( error ) => { toastNotifications . addDanger ( formatHttpError ( error ) ) ; } , [ toastNotifications ] ) ; const handleSearchQueryError = useCallback ( ( err ) => { const toastTitle = i18n . translate ( 'xpack.graph.errorToastTitle' , { defaultMessage : 'Graph Error' , description : '"Graph" is a product name and should not be translated.' , } ) ; if ( err instanceof Error ) { toastNotifications . addError ( err , { title : toastTitle , } ) ; } else { toastNotifications . addDanger ( { title : toastTitle , text : String ( err ) , } ) ; } } , [ toastNotifications ] ) ; const callNodeProxy = useCallback ( ( indexName , query , responseHandler ) => { const request = { body : JSON . stringify ( { index : indexName , query , } ) , } ; setLoading ( true ) ; return coreStart . http . post < { resp : { timed_out : unknown ; } ; } > ( '../api/graph/graphExplore' , request ) . then ( function ( data ) { const response = data . resp ; if ( response ?. timed_out ) { toastNotifications . addWarning ( i18n . translate ( 'xpack.graph.exploreGraph.timedOutWarningText' , { defaultMessage : 'Exploration timed out' , } ) ) ; } responseHandler ( response ) ; } ) . catch ( handleHttpError ) . finally ( ( ) => setLoading ( false ) ) ; } , [ coreStart . http , handleHttpError , toastNotifications ] ) ; const callSearchNodeProxy = useCallback ( ( indexName , query , responseHandler ) => { const request = { body : JSON . stringify ( { index : indexName , body : query , } ) , } ; setLoading ( true ) ; coreStart . http . post < { resp : unknown ; } > ( '../api/graph/searchProxy' , request ) . then ( function ( data ) { const response = data . resp ; responseHandler ( response ) ; } ) . catch ( handleHttpError ) . finally ( ( ) => setLoading ( false ) ) ; } , [ coreStart . http , handleHttpError ] ) ; return { loading , callNodeProxy , callSearchNodeProxy , handleSearchQueryError , } ; } ;