import { useEffect , useState } from 'react' ; import { IndexPattern , getServices } from '../../../opensearch_dashboards_services' ; import { DocProps } from './doc' ; import { OpenSearchSearchHit } from '../../doc_views/doc_views_types' ; export enum OpenSearchRequestState { Loading , NotFound , Found , Error , NotFoundIndexPattern } /**
 * helper function to build a query body for OpenSearch
 * https://opensearch.org/docs/latest/opensearch/query-dsl/index/
 */ export function buildSearchBody ( id , indexPattern ) { const computedFields = indexPattern . getComputedFields ( ) ; return { query : { ids : { values : [ id ] , } , } , stored_fields : computedFields . storedFields , _source : true , script_fields : computedFields . scriptFields , docvalue_fields : computedFields . docvalueFields , } ; } /**
 * Custom react hook for querying a single doc in OpenSearch
 */ export function useOpenSearchDocSearch ( { id , index , indexPatternId , indexPatternService , } ) { const [ indexPattern , setIndexPattern ] = useState < IndexPattern | null > ( null ) ; const [ status , setStatus ] = useState ( OpenSearchRequestState . Loading ) ; const [ hit , setHit ] = useState < OpenSearchSearchHit | null > ( null ) ; useEffect ( ( ) => { async function requestData ( ) { try { const indexPatternEntity = await indexPatternService . get ( indexPatternId ) ; setIndexPattern ( indexPatternEntity ) ; const { rawResponse } = await getServices ( ) . data . search . search ( { params : { index , body : buildSearchBody ( id , indexPatternEntity ) , } , } ) . toPromise ( ) ; const hits = rawResponse . hits ; if ( hits ?. hits ?. [ 0 ] ) { setStatus ( OpenSearchRequestState . Found ) ; setHit ( hits . hits [ 0 ] ) ; } else { setStatus ( OpenSearchRequestState . NotFound ) ; } } catch ( err ) { if ( err . savedObjectId ) { setStatus ( OpenSearchRequestState . NotFoundIndexPattern ) ; } else if ( err . status === 404 ) { setStatus ( OpenSearchRequestState . NotFound ) ; } else { setStatus ( OpenSearchRequestState . Error ) ; } } } requestData ( ) ; } , [ id , index , indexPatternId , indexPatternService ] ) ; return [ status , hit , indexPattern ] ; }