Value transformation / object mapping
See original GitHub issueHey! I just tried zod
and I quite enjoy it so far, great job! I have a feature request/discussion.
Problem: I would like my schema to not only validate data but transform it as well. A particular use case is that I would like to specify a mapping in my object schema.
One could imagine a type z.stringAsNumber()
which would parse strings like "123"
to a number 123
. Something like this is totally possible with io-ts
.
Or even more powerful case. Where object validation could remap keys:
const envSchema = z.object({
SERVER_HOST: z.string(),
PUBLIC_S3_URL: z.string(),
PRIVATE_BACKEND_URL: z.string(),
})
This schema is used to validate environment variables. It would be cool if I could specify a key mapping to end up with renamed keys in a parsed object for example (example API)
const envSchema = z.object({
serverHost: { value: z.string(), key: 'SERVER_HOST' },
publicS3: { value: z.string(), key: 'PUBLIC_S3_URL' }
privateBackendURL: { z.string(), key: 'PRIVATE_BACKEND_URL' }
})
I feel like this is a very common situation. Of course, it can be done manually after schema validation but I believe that it would be cool to support this one way or another. WDYT @vriad? Is this something that you want to support eventually?
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:13 (7 by maintainers)
Top GitHub Comments
@vriad just my 2cents as the yup author, distinctly split transforming and validating. mushing them together like Joi (and so yup) makes it really hard to type correctly and hard to reason about. It introduces oddities like having chaining order matter a lot when it shouldn’t for the output type. Some of this is actively making better TS support in yup harder, and while the API is nice, I do wish I made different choices 😛 and now it’s hard to make sweeping changes.
Also Zod is very cool 👍 i’m gonna ~steal~ borrow some ideas
Thanks for taking the time to write this up. I’m definitely dragging my feet on implementing something like this since it increases the complexity so significantly.
I’m still figuring out whether I want to go in this direction. That decision is primarily determine by whether I can find a way of doing this that I like. Muddying up the schema declaration API with a bunch of pairwise mapping functions (i.e.
stringToNumber
) sounds like a mess. I haven’t come up with a generalizable solution that I like yet, but I’ll leave this issue open so others can chime in with ideas/proposals.