import _ from 'lodash' ; import { IndexPattern } from './index_pattern' ; import { FieldFormatsContentType } from '../../../common' ; const formattedCache = new WeakMap ( ) ; const partialFormattedCache = new WeakMap ( ) ; export function formatHitProvider ( indexPattern , defaultFormat ) { function convert ( hit , val , fieldName , type = 'html' ) { const field = indexPattern . fields . getByName ( fieldName ) ; const format = field ? indexPattern . getFormatterForField ( field ) : defaultFormat ; return format . convert ( val , type , { field , hit , indexPattern } ) ; } function formatHit ( hit , type = 'html' ) { if ( type === 'text' ) { const flattened = indexPattern . flattenHit ( hit ) ; const result = { } ; for ( const [ key , value ] of Object . entries ( flattened ) ) { result [ key ] = convert ( hit , value , key , type ) ; } return result ; } const cached = formattedCache . get ( hit ) ; if ( cached ) { return cached ; } const partials = partialFormattedCache . get ( hit ) || { } ; partialFormattedCache . set ( hit , partials ) ; const cache = { } ; formattedCache . set ( hit , cache ) ; _ . forOwn ( indexPattern . flattenHit ( hit ) , function ( val , fieldName ? ) { if ( ! fieldName ) { return ; } const formatted = partials [ fieldName ] == null ? convert ( hit , val , fieldName ) : partials [ fieldName ] ; cache [ fieldName ] = partials [ fieldName ] = formatted ; } ) ; return cache ; } formatHit . formatField = function ( hit , fieldName ) { let partials = partialFormattedCache . get ( hit ) ; if ( partials && partials [ fieldName ] != null ) { return partials [ fieldName ] ; } if ( ! partials ) { partials = { } ; partialFormattedCache . set ( hit , partials ) ; } const val = fieldName === '_source' ? hit . _source : indexPattern . flattenHit ( hit ) [ fieldName ] ; return convert ( hit , val , fieldName ) ; } ; return formatHit ; }