import { get , isEmpty } from 'lodash' ; import type { SearchResponse } from 'kibana/server' ; import { overwrite } from '../../helpers' ; import type { Annotation } from '../../../../../common/types' ; interface AnnotationsBuckets { key : string ; hits : { hits : { hits : Array < { fields : Record < string , unknown [ ] > ; } > ; } ; } ; } const concatenateValues = ( values ) => values . join ( ',' ) ; export function getAnnotationBuckets ( resp , annotation ) { const buckets = get ( resp , `aggregations.${ annotation . id }.buckets` , [ ] ) as AnnotationsBuckets [ ] ; return buckets . filter ( ( bucket ) => ! isEmpty ( bucket . hits . hits . hits ) ) . map ( ( bucket ) => ( { key : bucket . key , docs : bucket . hits . hits . hits . map ( ( doc ) => Object . keys ( doc . fields ) . reduce ( ( acc , key ) => { overwrite ( acc , key , concatenateValues ( doc . fields [ key ] ) ) ; return acc ; } , { } ) ) , } ) ) ; }