import _ from 'lodash' ; import { IndexPattern } from './index_pattern' ; function flattenHit ( indexPattern , hit , deep ) { const flat = { } as Record < string , any > ; const fields = indexPattern . fields . getByName ; ( function flatten ( obj , keyPrefix = '' ) { keyPrefix = keyPrefix ? keyPrefix + '.' : '' ; _ . forOwn ( obj , function ( val , key ) { key = keyPrefix + key ; if ( deep ) { const field = fields ( key ) ; const isNestedField = field && field . type === 'nested' ; const isArrayOfObjects = Array . isArray ( val ) && _ . isPlainObject ( _ . first ( val ) ) ; if ( isArrayOfObjects && ! isNestedField ) { _ . each ( val , ( v ) => flatten ( v , key ) ) ; return ; } } else if ( flat [ key ] !== void 0 ) { return ; } const field = fields ( key ) ; const hasValidMapping = field && field . type !== 'conflict' ; const isValue = ! _ . isPlainObject ( val ) ; if ( hasValidMapping || isValue ) { if ( ! flat [ key ] ) { flat [ key ] = val ; } else if ( Array . isArray ( flat [ key ] ) ) { flat [ key ] . push ( val ) ; } else { flat [ key ] = [ flat [ key ] , val ] ; } return ; } flatten ( val , key ) ; } ) ; } ) ( hit . _source ) ; return flat ; } function decorateFlattenedWrapper ( hit , metaFields ) { return function ( flattened ) { _ . each ( metaFields , function ( meta ) { if ( meta === '_source' ) return ; flattened [ meta ] = hit [ meta ] ; } ) ; _ . forOwn ( hit . fields , function ( val , key ) { if ( key [ 0 ] === '_' && ! _ . includes ( metaFields , key ) ) return ; if ( Array . isArray ( val ) && val . length <= 1 ) { flattened [ key ] = val [ 0 ] ; } else { flattened [ key ] = val ; } } ) ; return flattened ; } ; } internal export function flattenHitWrapper ( indexPattern , metaFields = { } , cache = new WeakMap ( ) ) { return function cachedFlatten ( hit , deep = false ) { const decorateFlattened = decorateFlattenedWrapper ( hit , metaFields ) ; const cached = cache . get ( hit ) ; const flattened = cached || flattenHit ( indexPattern , hit , deep ) ; if ( ! cached ) { cache . set ( hit , { ... flattened } ) ; } return decorateFlattened ( flattened ) ; } ; } public export function createFlattenHitWrapper ( ) { const cache = new WeakMap ( ) ; return _ . partial ( flattenHitWrapper , _ , _ , cache ) ; }