From 976ad5aee3d34976b4be87b99071e1631e56ce89 Mon Sep 17 00:00:00 2001 From: Sam Chung Date: Mon, 8 Jan 2024 10:31:01 +1100 Subject: [PATCH] Ignore ZodNever and ZodUndefined (#202) --- README.md | 2 ++ src/create/schema/parsers/object.test.ts | 15 +++++++++++++++ src/create/schema/parsers/object.ts | 7 +++++++ src/create/schema/parsers/optional.ts | 6 +++++- 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6a133a6..a0427dd 100644 --- a/README.md +++ b/README.md @@ -521,6 +521,7 @@ For example in `z.string().nullable()` will be rendered differently - ZodLiteral - ZodNativeEnum - supporting `string`, `number` and combined enums. +- ZodNever - ZodNull - ZodNullable - ZodNumber @@ -543,6 +544,7 @@ For example in `z.string().nullable()` will be rendered differently - ZodTuple - `items` mapping for `.rest()` - `prefixItems` mapping for OpenAPI 3.1.0+ +- ZodUndefined - ZodUnion - By default it outputs an `allOf` schema. Use `unionOneOf` to change this to output `oneOf` instead. - ZodUnknown diff --git a/src/create/schema/parsers/object.test.ts b/src/create/schema/parsers/object.test.ts index d3b2c25..6f1ee56 100644 --- a/src/create/schema/parsers/object.test.ts +++ b/src/create/schema/parsers/object.test.ts @@ -199,4 +199,19 @@ describe('extend', () => { expect(result).toStrictEqual(expected); }); + + it('ignores ZodNever and ZodUndefined schemas', () => { + const expected: oas31.SchemaObject = { + type: 'object', + properties: { + a: { type: 'string' }, + }, + required: ['a'], + }; + const schema = z.object({ a: z.string(), b: z.undefined(), c: z.never() }); + + const result = createObjectSchema(schema, createOutputState()); + + expect(result).toStrictEqual(expected); + }); }); diff --git a/src/create/schema/parsers/object.ts b/src/create/schema/parsers/object.ts index c74bf07..b11c74c 100644 --- a/src/create/schema/parsers/object.ts +++ b/src/create/schema/parsers/object.ts @@ -185,6 +185,13 @@ export const mapProperties = ( ): oas31.SchemaObject['properties'] => Object.entries(shape).reduce>( (acc, [key, zodSchema]): NonNullable => { + if ( + isZodType(zodSchema, 'ZodNever') || + isZodType(zodSchema, 'ZodUndefined') + ) { + return acc; + } + acc[key] = createSchemaObject(zodSchema, state, [`property: ${key}`]); return acc; }, diff --git a/src/create/schema/parsers/optional.ts b/src/create/schema/parsers/optional.ts index d82afdb..0afa27b 100644 --- a/src/create/schema/parsers/optional.ts +++ b/src/create/schema/parsers/optional.ts @@ -14,7 +14,11 @@ export const isOptionalSchema = ( zodSchema: ZodTypeAny, state: SchemaState, ): boolean => { - if (isZodType(zodSchema, 'ZodOptional')) { + if ( + isZodType(zodSchema, 'ZodOptional') || + isZodType(zodSchema, 'ZodNever') || + isZodType(zodSchema, 'ZodUndefined') + ) { return true; }