colinhacks/zod

codegen zod validators - output definitions to file

Opened this issue · 0 comments

Is there a way to output the definition of a zod validator to a .ts file?

I am generating a zod validator from a json file that is supplied to us by a third party. (the json specifies validation requirements, it isn't data / the object structure itself)
It is easy to parse the json and make a zod object that validates correctly. However, I cannot find any way to write this definition to a .ts file so the validator (and the types inferred from it) can be used within the system.

Currently I have to build the validator by making an object of concatenated strings, such as:

const validator = {
    foo: "z.string()",
    bar: "z.number().nullable()",
};

then use JSON.stringify and a bunch of regex replaces, and write that to a file

for (const [conditionType, conditionValidator] of Object.entries(validators)) {
    const validatorName = `${conditionTypeToId(z.nativeEnum(ConditionTypes).parse(conditionType))}Validator`;

    stringValidatorsArray.push(formatValidator(
        `export const ${validatorName} = z.object(${JSON.stringify(conditionValidator)});`,
    ));
    validatorNames.push(validatorName);
}
function formatValidator(validator: string): string {
    // Remove double quotes from JSON.stringify
    validator = validator.replace(/"/g, "");

    // Replace single quotes with double quotes
    validator = validator.replace(/'/g, "\"");

    // Add newlines and indent each object property by 4 spaces outside of arrays
    validator = validator.replace(/,\s*(?![^[]*\])/g, ",\n    ");

    // Add newlines and indent each object property by 4 spaces, but not within arrays
    validator = validator.replace(/:\s*/g, ": ");
    validator = validator.replace(/{/g, "{\n    ");
    validator = validator.replace(/}/g, ",\n}");

    return validator;
};

I've been looking at the docs and I could build a parser that recursively inspects the validators properties using .shape, ._def, etc... and generates a stringified version of any zod object passed, but that would really not be ideal.

@colinhacks is there any way that a zod validator can easily output it's definition?