Best practices: Use schema validation along classes
See original GitHub issueHello,
This issue is not related to a Zod problem, but I’m sure people using the lib can help me ❤️
This is a simple Schema (we have to imagine it is more complex):
export const PersonSchema = z.object({
id: z.string(),
firstname: z.string(),
lastname: z.string()
});
export type PersonType = z.infer<typeof PersonSchema>;
On server side, when I get a POST request, I can validate the payload using:
const newPerson = PersonSchema.parse(payload);
Great, my noSQL database will stay clean !
But now, I want to use this on client-side. So I use the same method.
const newPerson = PersonSchema.parse(payload);
My front get a Person object now, but to display it, I would like to use a class method like this for example:
newPerson.getFullName();
But newPerson is not a class instance…
So far, I found those solutions:
Solution 1:
Create a class Person:
class PersonClass implements PersonType {
id: ZodString['_output'];
lastname: ZodString['_output'];
firstName: ZodString['_output'];
constructor(newPerson: PersonType) {
this.id = newPerson.contactEmail;
this.lastname = newPerson.lastname;
this.firstname = newPerson.firstname;
}
getFullName() {
return this.firstname + " " + this.lastname;
}
OR
class PersonClass implements PersonType {
id: z.infer<typeof PersonSchema.shape.name>;
lastname: z.infer<typeof PersonSchema.shape.name>;
firstName: z.infer<typeof PersonSchema.shape.name>;
constructor(newPerson: PersonType) {
this.id = newPerson.contactEmail;
this.lastname = newPerson.lastname;
this.firstname = newPerson.firstname;
}
getFullName() {
return this.firstname + " " + this.lastname;
}
}
I found this on the same subject:
https://github.com/colinhacks/zod/issues/38
But the more Person will have attributes, the more the class size is also growing. And I will have to parse my object, then to make an instance of the class…
Solution 2:
I don’t use classes, and I create a getFullName() methods like this:
const getFullName = (person: PersonType) => {return person.firstname + " " + person.lastname;}
So my question is:
How and when do you use Zod in your projects ?
Only to validate payloads ? How to use methods on parsed objects?
Issue Analytics
- State:
- Created 2 years ago
- Comments:5
Top GitHub Comments
This is a great idea ! I think I will use this “factory” to add all my “class” functions to all objects !
Closing, but feel free to add any additional thoughts here. If we want this to be an ongoing discussion point, we can also migrate this to a GitHub discussion.