import isWithinInterval from 'date-fns/isWithinInterval' ; import isEqual from 'date-fns/isEqual' ; import subMilliseconds from 'date-fns/subMilliseconds' ; import addMilliseconds from 'date-fns/addMilliseconds' ; import { getValidDate } from '@terascope/utils' ; import { isInfiniteMax , isInfiniteMin , ParsedRange } from 'xlucene-parser' ; import { BooleanCB } from '../interfaces' ; export function compareTermDates ( value ) { const nodeTermTime = convertDate ( value , 0 , true ) ; return function dateTerm ( date ) { const result = convertDate ( date , 0 , false ) ; if ( ! result ) return false ; return isEqual ( result , nodeTermTime ) ; } ; } function getRangeValues ( rangeQuery ) { let incMin = rangeQuery . gte == null ? 1 : 0 ; let incMax = rangeQuery . lte == null ? - 1 : 0 ; let minValue = rangeQuery . gte || rangeQuery . gt || '*' ; let maxValue = rangeQuery . lte || rangeQuery . lt || '*' ; if ( isInfiniteMin ( minValue ) ) { incMin = 0 ; minValue = new Date ( - 8640000000000000 ) ; } if ( isInfiniteMax ( maxValue ) ) { incMax = 0 ; maxValue = new Date ( 8640000000000000 ) ; } const start = convertDate ( minValue , incMin , true ) ; const end = convertDate ( maxValue , incMax , true ) ; return { start , end } ; } export function dateRange ( rangeQuery ) { const interval = getRangeValues ( rangeQuery ) ; isWithinInterval ( new Date ( ) , interval ) ; return function dateRangeTerm ( date ) : boolean { const result = convertDate ( date , 0 , false ) ; if ( ! result ) return false ; try { return isWithinInterval ( result , interval ) ; } catch ( err ) { return false ; } } ; } function convertDate ( val , inclusive , throwErr ) ; function convertDate ( val , inclusive , throwErr ) ; function convertDate ( val , inclusive , throwErr ) { const result = getValidDate ( val as any ) ; if ( result ) return handleInclusive ( result , inclusive ) ; if ( throwErr ) throw new Error ( `Invalid date format ${ val }` ) ; return undefined ; } function handleInclusive ( date , inclusive ) { if ( inclusive === 0 ) return date ; if ( inclusive < 0 ) return subMilliseconds ( date , inclusive ) ; return addMilliseconds ( date , inclusive ) ; }