UNPKG

@yobta/validator

Version:
34 lines (33 loc) 1.07 kB
import { isPlainObject } from '../_internal/isPlainObject/index.js'; import { handleUnknownError } from '../_internal/parseUnknownError/index.js'; import { rule } from '../rule/rule.js'; export const shapeMessage = 'Ivalid shape'; export const shape = (rulesMap, validationMessage = shapeMessage) => rule((value = '', context) => { if (value === '') { return undefined; } const err = new Error(validationMessage); if (!isPlainObject(value)) { throw err; } const result = { ...value }; for (const field in rulesMap) { const path = [...context.path, field]; const validate = rulesMap[field]; try { // @ts-ignore const next = value[field]; result[field] = validate({ ...context, data: value, field, path, value: next, })(next); } catch (error) { context.pushError(handleUnknownError({ error, field, path })); } } return result; });