import { FieldFilter , Filter } from '../types/filter' ; import { flatten } from 'lodash' ; import { generateJoi , JoiOptions } from './generate-joi' ; import Joi from 'joi' ; param { Filter } filter param { Record < string , any > } payload param { JoiOptions } options returns export function validatePayload ( filter , payload , options ? ) { const errors = [ ] ; /**
     * Note there can only be a single _and / _or per level
     */ if ( Object . keys ( filter ) [ 0 ] === '_and' ) { const subValidation = Object . values ( filter ) [ 0 ] as FieldFilter [ ] ; const nestedErrors = flatten < Joi . ValidationError > ( subValidation . map ( ( subObj ) => { return validatePayload ( subObj , payload , options ) ; } ) ) . filter ( ( err ? ) => err ) ; errors . push ( ... nestedErrors ) ; } else if ( Object . keys ( filter ) [ 0 ] === '_or' ) { const subValidation = Object . values ( filter ) [ 0 ] as FieldFilter [ ] ; const nestedErrors = flatten < Joi . ValidationError > ( subValidation . map ( ( subObj ) => validatePayload ( subObj , payload , options ) ) ) ; const allErrored = subValidation . length === nestedErrors . length ; if ( allErrored ) { errors . push ( ... nestedErrors ) ; } } else { const schema = generateJoi ( filter as FieldFilter , options ) ; const { error } = schema . validate ( payload , { abortEarly : false } ) ; if ( error ) { errors . push ( error ) ; } } return errors ; }