zod icon indicating copy to clipboard operation
zod copied to clipboard

Introduce data hydration

Open ArthurKa opened this issue 3 years ago • 3 comments

Implement data hydration.

For example, when you need to validate any input data and get string[] on output, without hydration you can only get validation error or set default value (if parse undefined), but with hydration if data validation fails it fallbacks on what you pass to .hydrate method.

const schema = z.string().hydrate(/* '' by default */).array().hydrate([]);

schema.parse(undefined); // => []
schema.parse({ a: 123 }); // => []
schema.parse([]); // => []
schema.parse(['asd']); // => ['asd']
schema.parse([1]); // => ['']
schema.parse([1, 'a', 2]); // => ['', 'a', '']

So on output you always have string[].

ArthurKa avatar Sep 20 '22 09:09 ArthurKa

Deploy Preview for guileless-rolypoly-866f8a ready!

Built without sensitive environment variables

Name Link
Latest commit 8deaea491dbe8e06fddb8efbc70e8986f0245544
Latest deploy log https://app.netlify.com/sites/guileless-rolypoly-866f8a/deploys/63298dfed629bf000982fc4d
Deploy Preview https://deploy-preview-1417--guileless-rolypoly-866f8a.netlify.app
Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site settings.

netlify[bot] avatar Sep 20 '22 09:09 netlify[bot]

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

stale[bot] avatar Dec 05 '22 13:12 stale[bot]

Please, review.

ArthurKa avatar Dec 05 '22 13:12 ArthurKa

Great idea and great PR. Ultimately this was implemented in #1537 as .catch and just landed in Zod 3.20. Thanks for the amazing work here and apologies for the delay in reviewing this.

colinhacks avatar Dec 12 '22 09:12 colinhacks

@colinhacks, thanks for your review, but I still recommend you to accept .hydrate method because it has some advantages comparing to implemented .catch one.

  1. For some schemas you can omit to put default values such as 0 for z.number.hydrate(), empty string for z.string.hydrate(), null, undefined, empty Map, Set, array and so on.
  2. It's covered with more test cases.
  3. If you pass the function into .hydrate it has input value as the first parameter for better experience typed as unknown. For example, you just can't implement such schema using .catch. method:
z.number().hydrate(e => Array.isArray(e) ? e.length : -1);

See? It accepts any number otherwise if input is an array the result will be its length, and -1 otherwise.

I updated it with recent changes in #1670.

ArthurKa avatar Dec 12 '22 14:12 ArthurKa