UNPKG

@vorms/resolvers

Version:
40 lines (36 loc) 1.02 kB
import { set } from '@vorms/core'; const toNestError = (errors) => { const fieldErrors = {}; for (const path in errors) { set(fieldErrors, path, errors[path]); } return fieldErrors; }; /** * Why `path!` ? because it could be `undefined` in some case * https://github.com/jquense/yup#validationerrorerrors-string--arraystring-value-any-path-string */ const parseErrorSchema = (error) => { return (error.inner || []).reduce((previous, error) => { if (!previous[error.path]) { previous[error.path] = error.message; } return previous; }, {}); }; const yupResolver = (schema) => async (values) => { try { await schema.validate(values, { strict: true, abortEarly: false, }); return {}; } catch (errors) { if (!errors.inner) { throw errors; } return toNestError(parseErrorSchema(errors)); } }; export { yupResolver };