Allow defining a different key into the final destination object after parsing
See original GitHub issueRight now zod is becoming more and more an integral part of all my projects, however, there’s still a pretty common use case that doesn’t have a direct mapping in zod, basically, allowing to validate a different schema than the output one.
Most of the times, in TypeScript codebases, interfacing with an API involves firing a fetch
request and validating the received data to make sure it corresponds to the shape we’re defining in our types. Zod is really great for this due to it’s practically 1:1 equivalence with TS typings. However, sometimes, the types we receive from the request don’t correspond directly to the types we’ve defined in our codebase (legacy code, different naming schemas, etc.) and that forces us to having to create yet another layer after validation to do processing.
So I was wondering, if it’d be possible and zod architecture would allow to define a way to “collect” keys from the input data and “assign” them to another key in the resulting data.
For example, let’s imagine we’re building a front-end app using TypeScript (camel case naming) and we request data to our back-end in Rails (snake case naming). Without the functionality described above, we have two solutions (without counting the one that is leaving the naming as is for obvious reasons):
- Validate the data and then transform the data, so our validators will refer to something that doesn’t really exist in the app
- Transform the data and then validate having to transform loosely typed data.
However, adding this functionality to zod, we could do it in just one single step and correctly coupling these two non-independent descriptions thus also providing clarity of intent.
An idea:
const UserSchema = z.object({
firstName: z.fromKey('first_name').string()
});
The code above will validate that first_name
is present and is a string, while at the same time, producing a firstName
key with the correctly validated data.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:13
- Comments:8 (1 by maintainers)
Top GitHub Comments
I’m not a fan of the
z.fromKey
proposal. This is a transformation that happens at the object-level, so defining the key remapping on a per-key basis is weird to me. I’d consider a.remap
method on ZodObject:Under the hood this would just be syntactic sugar on top of
.transform
. Thoughts @larsbs?@colinhacks Is there a remap method?