GitHub - ivangreene/java-to-zod: Convert POJOs to Zod schemas (original) (raw)
Java to Zod
Convert POJOs to Zod schemas. Uses JSR-380 (bean validation) annotationsto specify the constraints.
Why?
Write your schemas once, and use them for both frontend and backend validation.
Example
public class Person { @NotEmpty(message = "must not be empty") public String givenName;
@NotEmpty
public String surname;
@Positive(message = "must be positive")
public int age;
@Email(message = "must be a valid email")
public String email;
@NotNull
public AccountType accountType;
}
enum AccountType { PREMIUM, STANDARD, BASIC, }
Running the java-to-zod plugin will give you:
const PersonSchema = zod.object({ givenName: zod.string().min(1, { message: 'must not be empty' }), surname: zod.string().min(1), age: zod.number().int().positive({ message: 'must be positive' }), email: zod.string().email({ message: 'must be a valid email' }).optional().nullable(), accountType: zod.enum(['PREMIUM', 'STANDARD', 'BASIC']), });
Goes well withtypescript-generator, and shares many of the same configuration options for scanning source classes.
Example configuration for Maven plugin
sh.ivan java-to-zod-maven-plugin VERSION jackson2 ${project.basedir}/../frontend/generated-schemas.js sh.ivan.pojo.** generate generate process-classesSee plugin configuration docsfor all configuration properties.
Supported annotations
- AssertFalse
- AssertTrue
- DecimalMax - Not yet implemented
- DecimalMin - Not yet implemented
- Digits - Not yet implemented
- Future - Not yet implemented
- FutureOrPresent - Not yet implemented
- Max
- Min
- Negative
- NegativeOrZero
- NotBlank
- NotEmpty
- NotNull
- Null - Not yet implemented
- Past - Not yet implemented
- PastOrPresent - Not yet implemented
- Pattern
- No transformation is made to the regex pattern string. Keep in mind that the Java and JavaScript regex engines are not identical. The only flags supported are:
* CASE_INSENSITIVE (/i
)
* MULTILINE (/m
)
* DOTALL (/s
) - All other flags are ignored
- No transformation is made to the regex pattern string. Keep in mind that the Java and JavaScript regex engines are not identical. The only flags supported are:
- Positive
- PositiveOrZero
- Size