import dateMath from '@elastic/datemath' ; import { FILTER_OPERATORS , Operator } from './filter_operators' ; import { CidrMask , isFilterable , IIndexPattern , IFieldType , Ipv4Address , Filter , FieldFilter , } from '../../../../../common' ; export function getFieldFromFilter ( filter , indexPattern ) { return indexPattern . fields . find ( ( field ) => field . name === filter . meta . key ) ; } export function getOperatorFromFilter ( filter ) { return FILTER_OPERATORS . find ( ( operator ) => { return filter . meta . type === operator . type && filter . meta . negate === operator . negate ; } ) ; } export function getFilterableFields ( indexPattern ) { return indexPattern . fields . filter ( isFilterable ) ; } export function getOperatorOptions ( field ) { return FILTER_OPERATORS . filter ( ( operator ) => { return ! operator . fieldTypes || operator . fieldTypes . includes ( field . type ) ; } ) ; } export function validateParams ( params , type ) { switch ( type ) { case 'date' : const moment = typeof params === 'string' ? dateMath . parse ( params ) : null ; return Boolean ( typeof params === 'string' && moment && moment . isValid ( ) ) ; case 'ip' : try { return params . includes ( '/' ) ? Boolean ( new CidrMask ( params ) ) : Boolean ( new Ipv4Address ( params ) ) ; } catch ( e ) { return false ; } default : return true ; } } export function isFilterValid ( indexPattern ? , field ? , operator ? , params ? ) { if ( ! indexPattern || ! field || ! operator ) { return false ; } switch ( operator . type ) { case 'phrase' : return validateParams ( params , field . type ) ; case 'phrases' : if ( ! Array . isArray ( params ) || ! params . length ) { return false ; } return params . every ( ( phrase ) => validateParams ( phrase , field . type ) ) ; case 'range' : if ( typeof params !== 'object' ) { return false ; } return ( ( ! params . from || validateParams ( params . from , field . type ) ) && ( ! params . to || validateParams ( params . to , field . type ) ) ) ; case 'exists' : return true ; default : throw new Error ( `Unknown operator type: ${ operator . type }` ) ; } }