|
| 1 | +import { getSymbolName } from '../helpers'; |
| 2 | +import { StringValidator } from './validators'; |
| 3 | +import { BooleanValidator } from './validators'; |
| 4 | +import { NumberValidator } from './validators'; |
| 5 | +import { ValuePropertyValidationError } from './PropertyValidationError'; |
| 6 | + |
| 7 | +export const ERRORS = Symbol('errors'); |
| 8 | + |
| 9 | +export interface ValidationError extends ValuePropertyValidationError { |
| 10 | + targetProperty: string; |
| 11 | +} |
| 12 | + |
| 13 | +export interface Errors extends Array<ValidationError> {} |
| 14 | + |
| 15 | +export interface Validation { |
| 16 | + [ERRORS]: Errors; |
| 17 | +} |
| 18 | + |
| 19 | +export function targetContainsErrors(target: any): target is Validation { |
| 20 | + return target && target[ERRORS] && target[ERRORS].length > 0; |
| 21 | +} |
| 22 | + |
| 23 | +export function formatter(error: ValidationError) { |
| 24 | + const { value, targetProperty, type } = error; |
| 25 | + return `Invalid value ${value} supplied to : [⚠️ Schema With Type] at property ${targetProperty}. Expecting type ${getSymbolName(type)}`; |
| 26 | +} |
| 27 | +export function reporter(target: any) { |
| 28 | + if (!targetContainsErrors(target)) return []; |
| 29 | + |
| 30 | + const errors = target[ERRORS]; |
| 31 | + return errors.map(formatter); |
| 32 | +} |
| 33 | + |
| 34 | +export function parse(value: any, type: symbol) { |
| 35 | + if (type === StringValidator.type) { |
| 36 | + return StringValidator.validateAndParse(value); |
| 37 | + } else if (type === NumberValidator.type) { |
| 38 | + return NumberValidator.validateAndParse(value); |
| 39 | + } else if (type === BooleanValidator.type) { |
| 40 | + return BooleanValidator.validateAndParse(value); |
| 41 | + } |
| 42 | +} |
0 commit comments