colinhacks / zod

TypeScript-first schema validation with static type inference
https://zod.dev
MIT License
33.09k stars 1.15k forks source link

Proposal: Ability to extract certain values from the validated objects while parsing #3642

Open nikrabaev opened 2 months ago

nikrabaev commented 2 months ago

I'm working on a project with a large number of Zod schemas. The objects we're validating contain IDs of different database entities. After calling parse(), we additionally go over all objects and collect all IDs of the same kind in an array to bulk-load them from the database in a single query.

While exploring other validation libraries, I found a very interesting any.artifact(id) method in Joi that would allow me to simplify the validation code significantly by shifting the responsibility of value extraction onto the validation schema.

I searched through Zod's documentation but haven't found anything similar. Here's a simple example of how I imagine this feature in Zod:

const transferSchema = z.object({
  senderId: z.number().collect('userIds'), // 'userIds' is the name of the collection to which the value should be added
  recipientId: z.number().collect('userIds'),
  amount: z.number(),
});

const parseResult = transferSchema.safeParse({ // using safeParse as it returns the data wrapped in an object that can be extended
  senderId: 1,
  recipientId: 2,
  amount: 200
});

const userIds = parseResult.collections.userIds; // accessing values of the userIds collection - [1, 2]

const users = await getUsers(userIds); // loading users from the DB

I've already implemented this in Zod as a proof-of-concept: see my commit. However, a lot of work still needs to be done before it can be submitted to the official repo. I need to know if my proposal aligns with the maintainer's vision of Zod before further investing in the development of this feature.

I'd also love to hear what the community thinks about it.