Files
directus/packages/shared/src/utils/validate-payload.ts
Nitwel 4fd9f4c31c Add Filter interface (#7492)
* initial tests and preparation for filter interface

* get basic structure down

* improve visuals and interaction

* stop modifying props 🙃

* update logic blocks style

* clean up filter interface

* lint css

* support m2a and simplify visited relations

* allow for recursive loading of fields

* use filter interface on conditions

* Use dynamic useFilterTree instead of old one (#7569)

* use advanced field tree on field template

* update to advanced field tree

* remove old useFieldTree

* update to new design

* add border on nested nodes

* tweak styling

* Fix linter warnings

* Fix field-setup

* clean up interface

* clean up interface

* clean up and rename files

* clean up code

* use default filter structure

* fix changing fields

* Add monospace style option to tooltips

* Various small stylistic tweaks

* Add menu placement

* Cleanup "big interface" usage

* Remove seamless

* Add dropdown on add filter

* Cleanup import/export, add v-select-placeholder-co

* Fix staging issue

* Allow overriding preview slow, fix padding

* Show field path inline

* Cleanup empty state

* Use new filter-interface in permissions setup

Co-authored-by: rijkvanzanten <rijkvanzanten@me.com>
2021-09-30 17:17:29 -04:00

59 lines
1.6 KiB
TypeScript

import { FieldFilter, Filter } from '../types/filter';
import { flatten } from 'lodash';
import { generateJoi, JoiOptions } from './generate-joi';
import Joi from 'joi';
/**
* Validate the payload against the given filter rules
*
* @param {Filter} filter - The filter rules to check against
* @param {Record<string, any>} payload - The payload to validate
* @param {JoiOptions} [options] - Optional options to pass to Joi
* @returns Array of errors
*/
export function validatePayload(
filter: Filter,
payload: Record<string, any>,
options?: JoiOptions
): Joi.ValidationError[] {
const errors: Joi.ValidationError[] = [];
/**
* 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: Record<string, any>) => {
return validatePayload(subObj, payload, options);
})
).filter((err?: Joi.ValidationError) => 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: Record<string, any>) => 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;
}