import { i18n } from '@osd/i18n' ; import { IAggConfig } from '../agg_config' ; import { SavedObjectNotFound } from '../../../../../opensearch_dashboards_utils/common' ; import { BaseParamType } from './base' ; import { propFilter } from '../utils' ; import { OSD_FIELD_TYPES } from '../../../osd_field_types/types' ; import { isNestedField , IndexPatternField } from '../../../index_patterns/fields' ; const filterByType = propFilter ( 'type' ) ; export type FieldTypes = OSD_FIELD_TYPES | OSD_FIELD_TYPES [ ] | '*' ; export type IFieldParamType = FieldParamType ; export class FieldParamType extends BaseParamType { required = true ; scriptable = true ; filterFieldTypes : FieldTypes ; onlyAggregatable : boolean ; constructor ( config ) { super ( config ) ; this . filterFieldTypes = config . filterFieldTypes || '*' ; this . onlyAggregatable = config . onlyAggregatable !== false ; if ( ! config . write ) { this . write = ( aggConfig , output ) => { const field = aggConfig . getField ( ) ; if ( ! field ) { throw new TypeError ( i18n . translate ( 'data.search.aggs.paramTypes.field.requiredFieldParameterErrorMessage' , { defaultMessage : '{fieldParameter} is a required parameter' , values : { fieldParameter : '"field"' , } , } ) ) ; } if ( field . scripted ) { output . params . script = { source : field . script , lang : field . lang , } ; } else { output . params . field = field . name ; } } ; } this . serialize = ( field ) => { return field . name ; } ; this . deserialize = ( fieldName , aggConfig ? ) => { if ( ! aggConfig ) { throw new Error ( 'aggConfig was not provided to FieldParamType deserialize function' ) ; } const field = aggConfig . getIndexPattern ( ) . fields . getByName ( fieldName ) ; if ( ! field ) { throw new SavedObjectNotFound ( 'index-pattern-field' , fieldName ) ; } const validField = this . getAvailableFields ( aggConfig ) . find ( ( f ) => f . name === fieldName ) ; if ( ! validField ) { throw new Error ( i18n . translate ( 'data.search.aggs.paramTypes.field.invalidSavedFieldParameterErrorMessage' , { defaultMessage : 'Saved field "{fieldParameter}" is invalid for use with the "{aggType}" aggregation. Please select a new field.' , values : { fieldParameter : fieldName , aggType : aggConfig ?. type ?. title , } , } ) ) ; } return validField ; } ; } /**
     * filter the fields to the available ones
     */ getAvailableFields = ( aggConfig ) => { const fields = aggConfig . getIndexPattern ( ) . fields ; const filteredFields = fields . filter ( ( field ) => { const { onlyAggregatable , scriptable , filterFieldTypes } = this ; if ( ( onlyAggregatable && ( ! field . aggregatable || isNestedField ( field ) ) ) || ( ! scriptable && field . scripted ) ) { return false ; } return filterByType ( [ field ] , filterFieldTypes ) . length !== 0 ; } ) ; return filteredFields ; } ; }