import { i18n } from '@kbn/i18n' ; import { useAppContext } from '../contexts/app_context' ; import { checkForParseErrors } from '../lib' ; import { ShardSerialized } from '../types' ; interface Args { query : string ; index : string ; } interface ReturnValue { data : ShardSerialized [ ] | null ; error ? : string ; } const extractProfilerErrorMessage = ( e ) : string | undefined => { if ( e . body ?. attributes ?. error ?. reason ) { const { reason , line , col } = e . body . attributes . error ; if ( typeof line === 'number' && typeof col === 'number' ) { return `${ reason } at line: ${ line - 1 } col: ${ col }` ; } } if ( e . body ?. message ) { return e . body . message ; } return ; } ; export const useRequestProfile = ( ) => { const { http , notifications , getLicenseStatus } = useAppContext ( ) ; const licenseEnabled = getLicenseStatus ( ) . valid ; return async ( { query , index } ) : Promise < ReturnValue > => { if ( ! licenseEnabled ) { return { data : null } ; } const { error , parsed } = checkForParseErrors ( query ) ; if ( error ) { notifications . addError ( error , { title : i18n . translate ( 'xpack.searchProfiler.errorToastTitle' , { defaultMessage : 'JSON parse error' , } ) , } ) ; return { data : null } ; } if ( parsed . profile && parsed . profile . shards ) { return { data : parsed . profile . shards } ; } const payload = { query : parsed } ; if ( index == null || index === '' ) { payload . index = '_all' ; } else { payload . index = index ; } try { const resp = await http . post < { ok : true ; resp : { profile : { shards : ShardSerialized [ ] ; } ; } ; } | { ok : false ; err : { msg : string ; } ; } > ( '../api/searchprofiler/profile' , { body : JSON . stringify ( payload ) , headers : { 'Content-Type' : 'application/json' } , } ) ; if ( ! resp . ok ) { return { data : null , error : resp . err . msg } ; } return { data : resp . resp . profile . shards } ; } catch ( e ) { const profilerErrorMessage = extractProfilerErrorMessage ( e ) ; if ( profilerErrorMessage ) { notifications . addError ( e , { title : e . message , toastMessage : profilerErrorMessage , } ) ; } else { notifications . addError ( e , { title : i18n . translate ( 'xpack.searchProfiler.errorSomethingWentWrongTitle' , { defaultMessage : 'Something went wrong' , } ) , } ) ; } return { data : null } ; } } ; } ;