UNPKG

@jay-js/system

Version:

A powerful and flexible TypeScript library for UI, state management, lazy loading, routing and managing draggable elements in modern web applications.

66 lines 3.41 kB
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; /** * Creates a resolver function for validating form values using a Zod schema. * The type of form values is automatically inferred from the schema. * * @template TSchema - The Zod schema type. * @param {TSchema} schema - The Zod schema to validate the form values against. * @returns {TResolver<T>} A resolver function that validates the form values and returns validation errors, if any. * * The resolver supports validating either the entire form or a single field: * - If `fieldName` is provided, only the specified field is validated. * - If `fieldName` is not provided, the entire form is validated. * * The returned resolver function: * - Accepts the form values and an optional field name. * - Returns an object containing an array of validation errors, or an empty array if validation passes. */ export function zodResolver(schema) { return (values, fieldName) => __awaiter(this, void 0, void 0, function* () { try { if (fieldName) { // Para validação de campo único, validamos o objeto inteiro e depois filtramos try { yield schema.parseAsync(values); return { errors: [] }; } catch (error) { // Filtra apenas os erros do campo específico if ((error === null || error === void 0 ? void 0 : error.issues) && Array.isArray(error.issues)) { const fieldErrors = error.issues .map((issue) => ({ path: Array.isArray(issue.path) ? issue.path.join(".") : String(issue.path || "unknown"), message: issue.message || "Validation error", })) .filter((err) => err.path === fieldName || err.path.startsWith(`${fieldName}.`)); return { errors: fieldErrors }; } throw error; } } else { yield schema.parseAsync(values); return { errors: [] }; } } catch (error) { if ((error === null || error === void 0 ? void 0 : error.issues) && Array.isArray(error.issues)) { const errors = error.issues.map((issue) => ({ path: Array.isArray(issue.path) ? issue.path.join(".") : String(issue.path || "unknown"), message: issue.message || "Validation error", })); return { errors }; } return { errors: [{ path: "unknown", message: "Unknown error" }] }; } }); } //# sourceMappingURL=zod-resolver.js.map