Zod chain for union types#312
Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
| return code.assign(type.toString()); | ||
| const chain = getZodChain({ | ||
| schema: type.schema as SchemaObject, | ||
| meta: { ...meta, isRequired: true }, |
There was a problem hiding this comment.
I'm admittendly not entirely sure why isRequired: true is needed here and in the other places I added getZodChain calls. I tried excluding it at first, but it resulted in many test failures, and including it gave the results I was expecting.
| const schemaType = type.schema.type.toLowerCase() as NonNullable<typeof schema.type>; | ||
| isObject = !isPrimitiveType(schemaType); | ||
| } | ||
| } |
There was a problem hiding this comment.
isObject was unused, so this if/else to set its value was unneeded.
| schemas: { | ||
| Settings: "z.object({ theme_color: z.string(), features: Features.min(1) }).partial().passthrough()", | ||
| Author: "z.object({ name: z.union([z.string(), z.number()]).nullable(), title: Title.min(1).max(30), id: Id, mail: z.string(), settings: Settings }).partial().passthrough()", | ||
| Author: "z.object({ name: z.union([z.string().nullable(), z.number()]).nullable(), title: Title.min(1).max(30), id: Id, mail: z.string(), settings: Settings }).partial().passthrough()", |
There was a problem hiding this comment.
Up on line 69 you'll see Author's name property is set to nullable: true, so before this test was asserting union types did not have the chained validation applied to their sub-types
| const nulltype = z.object({}).partial().passthrough(); | ||
| const anyOfType = z.union([ | ||
| z.object({}).partial().passthrough(), | ||
| z.object({}).partial().passthrough().nullable(), |
There was a problem hiding this comment.
Same here. On line 21 of this file, the anyOf type has nullable: true, so this test was asserting a lack of the support being added in this PR.
The various chained validations were not being applied to the zod schemas generated by the use of
oneOf,allOf, andanyOfin an OpenAPI spec. For example, this spec:Woud generate this:
Where the expected output is this (which includes
min(1)for the first string type:This PR addresses this by making using of
getZodChainto append the chained validators to the sub-types within the composed types.