How to pick nested schemas from a global schema but keeping the original property path for errors? #2992
-
Hey, first of all: Zod is a great library and I am really happy to have found it! I have a huge object with multiple nested levels whereby the properties themselves can be objects again or also an array of objects. A snippet of the object's properties looks like this:
Each object being used is built from a class and each class has setter methods for updating the individual variables. In the setter methods I am parsing against the repsective subschema that is connected to that variable. Currently these schemas are added individually in each setter method and are not stemming from a centralized global schema. Therefore, when an error is thrown the error path variable contains an empty array since the parsed schema is not embedded in a superior structure. I would like to implement a global schema (see code snippet above) instead of defining all these little subschemas for each property setter individually, especially since I am using Zod as the single source of truth which includes inferring the TypeScript types from it. Doing so should also enable Zod to output the path to the variable when an error occurs. Now the problem: When a nested value e.g. _units is updated it would be sufficient to just parse against the subschema that is defined for the _units property: z.number().nonnegative().nullable(). I know that I can access the subschema using the .pick() method or by recursively accessing the shape properties of the global schema but the problem is when I do this, then the path holding the information where the targeted variable resided within the global schema is lost (e.g. the path should be Of course, I could go ahead now and just always parse all existing data against the global schema to keep the path information but considering that only a single value is updated it feels like a complete overkill to always parse the whole object especially since it is a quite complex structure with many different properties and schemas. After I googled quite a while trying to search for a solution but not finding anything helpful I would really appreciate if somebody could give me a hint how to overcome this problem. Looking forward to any kind of help that you could give me. Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Unfortunately, I don't think this is possible. |
Beta Was this translation helpful? Give feedback.
Unfortunately, I don't think this is possible.