question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Best practices: Use schema validation along classes

See original GitHub issue

Hello,

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:closed
  • Created 2 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
X-Titouancommented, Sep 16, 2021
export function create(data: unknown) {
  return {
    ...person.parse(data),
    getFullName: function (this: Person) {
      return `${this.firstName} ${this.lastName}`;
    }
  };
}

This is a great idea ! I think I will use this “factory” to add all my “class” functions to all objects !

0reactions
scotttrinhcommented, Sep 16, 2021

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

A Vocabulary for Structural Validation of JSON - JSON Schema
JSON Schema (application/schema+json) has several purposes, one of which is JSON instance validation. This document specifies a vocabulary for JSON Schema ...
Read more >
Designing the perfect Typescript schema validation library
When I started my quest to find the ideal schema declaration/validation library, I assumed the hardest part would be identifying the Most Great ......
Read more >
Adobe Experience Platform Schema Creation to Validation
Best Practices – Adobe Experience Platform Schema Creation to Validation · Prepare Before Creation · Plan, Determine then Build · Decide Data Type....
Read more >
Best Practices (Design, Schema, Query) - YouTube
GSQL is a user-friendly, highly expressive, and Turing-complete graph query language. Although learning GSQL is relatively easy, ...
Read more >
Schema validation in TypeScript with Zod - LogRocket Blog
Although it is best to use Zod along with TypeScript, if you want a limited, Zod-only type safety, you can use it in...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found