UNPKG

@vtaits/form-schema

Version:

Serialization and parsing form values by schema

165 lines (164 loc) 3.6 kB
import { defaultErrorMessages } from "./chunk-O5F4Y5EZ.js"; import { parseSingle, serializeSingle, setFieldErrors, validateBeforeSubmit } from "./chunk-3DE3JEEE.js"; // src/fields/list/list.ts import { isPromise } from "es-toolkit"; import { unwrapOr } from "krustykrab"; function prepareValue(value) { const unwrapped = unwrapOr(value, []); if (Array.isArray(unwrapped)) { return unwrapped; } return [unwrapped]; } var list = { createGetFieldSchema: ({ fieldSchema: { itemSchema } }) => { return () => itemSchema; }, serializerSingle: ({ value, name, getFieldSchema, getFieldType, parents }) => { const arrayValue = prepareValue(value); return Promise.all( arrayValue.map( (arrayValueItem, index) => serializeSingle({ values: { [index]: arrayValueItem }, name: String(index), getFieldSchema, getFieldType, parents: [ ...parents, { name, values: arrayValue } ] }) ) ); }, parserSingle: ({ value, name, getFieldSchema, getFieldType, parents }) => { const arrayValue = prepareValue(value); const preparsed = arrayValue.map( (arrayValueItem, index) => parseSingle({ values: { [index]: arrayValueItem }, name: String(index), getFieldSchema, getFieldType, parents: [ ...parents, { name, values: arrayValue } ] }) ); if (preparsed.some(isPromise)) { return Promise.all(preparsed); } return preparsed; }, validatorBeforeSubmit: async ({ value, name, setCurrentError, setError, fieldSchema, getFieldSchema, getFieldType, parents }) => { const { errorMessages: errorMessagesParam, required, maxLength, minLength } = fieldSchema; const errorMessages = { ...defaultErrorMessages, ...errorMessagesParam }; const arrayValue = prepareValue(value); if (arrayValue.length === 0) { if (required) { setCurrentError(errorMessages.required); } return; } if (minLength && arrayValue.length < minLength) { setCurrentError(errorMessages.minLength(minLength)); } if (maxLength && arrayValue.length > maxLength) { setCurrentError(errorMessages.maxLength(maxLength)); } const nextParents = [ ...parents, { name, values: arrayValue } ]; await validateBeforeSubmit({ setError, values: arrayValue, names: Object.keys(arrayValue), getFieldSchema, getFieldType, parents: nextParents }); }, errorsSetter: async ({ name, setError, errors, getFieldSchema, getFieldType, value, rawValue, parents }) => { const arrayValue = prepareValue(rawValue); const names = Object.keys(arrayValue); const nextParents = [ ...parents, { name, values: arrayValue } ]; const currentErrors = errors[name]; if (typeof currentErrors === "string") { setError(name, parents, currentErrors); return; } await setFieldErrors({ setError, errors: errors[name] || {}, names, getFieldSchema, getFieldType, values: prepareValue(value), rawValues: arrayValue, parents: nextParents }); } }; export { list }; //# sourceMappingURL=fields_list.js.map