@conform-to/zod
Version:
Conform helpers for integrating with Zod
60 lines (55 loc) • 1.83 kB
JavaScript
import { objectWithoutProperties as _objectWithoutProperties } from '../_virtual/_rollupPluginBabelHelpers.mjs';
import { appendPath } from '@conform-to/dom/future';
var _excluded = [""];
/**
* Transforms Zod validation results into Conform's error format.
*
* **Example:**
* ```ts
* const result = schema.safeParse(formData);
* const error = formatResult(result);
* ```
*/
function formatResult(result, options) {
var error = null;
var value = undefined;
if (!result.success) {
var errorByName = {};
for (var _issue of result.error.issues) {
var _errorByName$_name;
var _name = _issue.path.reduce((name, segment) => {
if (typeof segment === 'symbol') {
throw new Error('Symbol path segments are not supported. Received segment: ' + segment.toString());
}
return appendPath(name, segment);
}, '');
(_errorByName$_name = errorByName[_name]) !== null && _errorByName$_name !== void 0 ? _errorByName$_name : errorByName[_name] = [];
errorByName[_name].push(_issue);
}
var _Object$entries$reduc = Object.entries(errorByName).reduce((result, _ref) => {
var [name, issues] = _ref;
if (issues.length > 0) {
result[name] = options !== null && options !== void 0 && options.formatIssues ? options.formatIssues(issues, name) : issues.map(issue => issue.message);
}
return result;
}, {}),
{
'': formErrors = null
} = _Object$entries$reduc,
fieldErrors = _objectWithoutProperties(_Object$entries$reduc, _excluded);
error = {
formErrors,
fieldErrors
};
} else {
value = result.data;
}
if (!(options !== null && options !== void 0 && options.includeValue)) {
return error;
}
return {
error,
value
};
}
export { formatResult };