UNPKG

@yobta/validator

Version:
34 lines (33 loc) 1.12 kB
import { isPlainObject } from '../_internal/isPlainObject/index.js'; import { handleUnknownError } from '../_internal/parseUnknownError/index.js'; import { rule } from '../rule/rule.js'; export const asyncShapeMessage = 'Invalid shape'; export const asyncShape = (rulesSet, validationMessage = asyncShapeMessage) => rule(async (value = '', context) => { if (value === '') { return undefined; } if (!isPlainObject(value)) { throw new Error(validationMessage); } const result = { ...value }; for await (const field of Object.keys(rulesSet)) { const path = [...context.path, field]; const validate = rulesSet[field]; const next = value[field]; try { const valid = await validate({ ...context, data: value, field, path, value: next, })(next); // @ts-ignore result[field] = valid; } catch (error) { context.pushError(handleUnknownError({ error, field, path })); } } return result; });