Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

codegen zod validators - output definitions to file #3912

Open
EllipticElysium-idol opened this issue Dec 16, 2024 · 0 comments
Open

codegen zod validators - output definitions to file #3912

EllipticElysium-idol opened this issue Dec 16, 2024 · 0 comments

Comments

@EllipticElysium-idol
Copy link

EllipticElysium-idol commented Dec 16, 2024

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant