Ask questionsGuidance on creating slight schema variants for varied contexts

I am interested in using zod for frontend, API, and backend validation.

For example, a browser might validate user inputs live as they are changed on the page. The user hits "submit" which sends the data to the API. The API runs its own validations on this data that may be somewhat different. The API changes the data slightly to conform with the backend needs. The backend has a similar schema, but there are some small differences.

Differences might be things like:

  • Adding a field deep in the schema
  • Swapping a foreign key ID for an object pulled from some other location
  • API allows partial inputs for updates, but the backend sometimes requires complete inputs. For example, take a blog post draft that can be missing a title field, but the backend requires a title to be persisted before publishing.

I'm not necessarily looking for changes to the library, but rather recommended patterns through documentation, blog posts, etc. I see that zod supports merging, masking, and extending, but am looking for higher level guidance on patterns for this type of use case. I can see schema sharing as something that could potentially make a codebase much more complex without due care. The guidance here might be to create separate schemas because the costs of coupling schemas across contexts is too high!

There may also be features that could be added to zod that make this use case easier.


Answer questions chrbala

Yeah, agreed that at this point there isn't really an obvious action to take here. From investigating this, I've found that it's mostly easiest to make shared types from the leaf nodes up as high as what is fully shared, then do a hard fork where the types diverge. It can get pretty redundant with deeply nested types that diverge near the leaves, but I've found that the redundancy is the clearest way to represent this, rather than abstractions or core feature additions.


Related questions

No questions were found.
Github User Rank List