-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.ts
29 lines (23 loc) · 949 Bytes
/
validator.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { validate, ValidationError as ClassValidatorValidationError, ValidatorOptions } from 'class-validator';
import { ValidationError } from '../../contracts/errors/validation.error';
/**
* Validates an object with class-validator [[`validate`]]
* @param object The object to validate
* @param options validation options
*
* @category Helpers
*/
export const validator = async (object: object, options?: ValidatorOptions) => {
const validationErrors: ClassValidatorValidationError[] = await validate(object, options);
if (validationErrors.length > 0) {
const errors = validationErrors.reduce(map, {});
throw new ValidationError(errors);
}
};
const reduce = (errors: ClassValidatorValidationError[]) => {
return errors.reduce(map, {});
};
const map = (m: any, error: ClassValidatorValidationError) => {
m[error.property] = error.constraints ? Object.values(error.constraints) : reduce(error.children);
return m;
};