sanity-codegen
sanity-codegen copied to clipboard
Generate runtime validators for data auditing
This is just an idea I had and I wanted to create a reminder for myself to explore.
Similar to TypeScript itself, Sanity Codegen goes off of the assumption that the shape of your data matches what you assert it to in the schema but that's not a guarantee that the data will match. This is a perfectly fine assumption given the contains of the studio validation but it's very possible that a bad migration may leave certain documents incorrect.
Since we're already in the space of parsing the schema, I think there's potential for autogenerating runtime validators from the schemas. This way we could audit our data after migrations to ensure conformance to the schema and thus the generated types.
I just found this package and am excited to use it! I'd be happy to contribute. I have been pondering something similar for a while, so I'm glad I found this before starting my own project from scratch :)
Do you have any thoughts on how this should work?
For tooling, I'm a big fan of zod - it's lightweight, TS-first, and well-maintained.
I was thinking it could work via codegen actually. The next version of Sanity Codegen has a separate normalization and extraction step that could be used as an input to generate functions that validate documents (the extraction step shims out the studio env and pulls out a JSON representation of the schema). Then those functions could be run outside of the studio (maybe via CLI?) to generate reports or similar.
I've never heard of zod but I like it! (in fact, you make me regret using joi.js on a lot of recent projects lol). A possible path could be to use the result of the normalize/extraction step to generate zod schemas, though that path seems slightly redundant given that we don't need the ability to go from zod schema => typescript types
but regardless normalized sanity schema => X validator library schema
seems like a very plausible way to go about this.
If you'd like to work on this feature, I'd love to connect and this effort going. Feel free to shoot me an email at [email protected]