@conform-to/zod
Version:
Conform helpers for integrating with Zod
59 lines (52 loc) • 1.69 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var _rollupPluginBabelHelpers = require('../_virtual/_rollupPluginBabelHelpers.js');
var future = require('@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 = future.formatPath(_issue.path);
(_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 = _rollupPluginBabelHelpers.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
};
}
exports.formatResult = formatResult;