@advidi-network/zod-to-reactive-form
Version:
Zod to Reactive Form conversion library
56 lines (48 loc) • 1.94 kB
JavaScript
import { FormGroup, AbstractControl, FormControl, Validators, FormArray } from '@angular/forms';
import { z } from 'zod';
function createFormGroup(schema, overrides, options, generatorOptions) {
return new FormGroup(Object.entries(schema.shape).reduce((acc, [key, shapeSchema]) => {
const overrideOrOption = overrides?.[key];
if (overrideOrOption instanceof AbstractControl) {
acc[key] = overrideOrOption;
}
else {
acc[key] = createZodControl(shapeSchema, { ...generatorOptions, ...overrideOrOption });
}
return acc;
}, {}), options);
}
function createFormControl(schema, overrides) {
const { value = null, disabled = false } = overrides ?? {};
const isRequired = overrides?.isRequired ?? ((schema) => !schema.isOptional());
return new FormControl({ value, disabled }, {
nonNullable: !(schema instanceof z.ZodNullable),
...overrides,
validators: (isRequired(schema) ? [Validators.required] : []).concat(overrides?.validators ?? []),
});
}
function createZodControl(schema, options) {
if (schema instanceof z.ZodObject) {
return createFormGroup(schema, options);
}
else if (schema instanceof z.ZodArray) {
return createFormArray(schema, options);
}
return createFormControl(schema, options);
}
function createFormArray(schema, overrides, options, generatorOptions) {
const formArray = new FormArray([], options);
const element = schema.element;
overrides?.forEach((override) => {
return formArray.push(override instanceof AbstractControl ? override : createZodControl(element, generatorOptions));
});
return formArray;
}
/*
* Public API Surface of zod-to-reactive-form
*/
/**
* Generated bundle index. Do not edit.
*/
export { createFormArray, createFormControl, createFormGroup };
//# sourceMappingURL=advidi-network-zod-to-reactive-form.mjs.map