Introduce data hydration
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[].
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...Use your smartphone camera to open QR code link. |
To edit notification comments on pull requests, go to your Netlify site settings.
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.
Please, review.
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, thanks for your review, but I still recommend you to accept .hydrate method because it has some advantages comparing to implemented .catch one.
- For some schemas you can omit to put default values such as
0forz.number.hydrate(), empty string forz.string.hydrate(),null,undefined, empty Map, Set, array and so on. - It's covered with more test cases.
- If you pass the function into
.hydrateit has input value as the first parameter for better experience typed asunknown. 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.