From b49a5a74f4e3a65b14905427c8b86be8b129a8e3 Mon Sep 17 00:00:00 2001 From: Sam Chung Date: Sun, 15 Dec 2024 00:03:45 +1100 Subject: [PATCH] Update example types (#374) --- src/extendZod.test.ts | 25 +++++++++++++++++++++++++ src/extendZodTypes.ts | 8 +++++--- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/src/extendZod.test.ts b/src/extendZod.test.ts index faea140..0f35a13 100644 --- a/src/extendZod.test.ts +++ b/src/extendZod.test.ts @@ -89,4 +89,29 @@ describe('extendZodWithOpenApi', () => { expect(barString._def.zodOpenApi?.openapi?.effectType).toBe('input'); }); + + it('makes a date example accept strings', () => { + const fooString = z.union([z.date().optional(), z.string(), z.null()]); + + const barString = fooString.openapi({ + examples: [null, '2021-01-01'], + }); + + expect(barString._def.zodOpenApi?.openapi?.examples).toEqual([ + null, + '2021-01-01', + ]); + }); + + it('makes allows example to accept undefined but forbids undefined in examples', () => { + const fooString = z.union([z.date().optional(), z.string(), z.null()]); + + const barString = fooString.openapi({ + example: undefined, + // @ts-expect-error - Testing types + examples: [undefined], + }); + + expect(barString._def.zodOpenApi?.openapi?.example).toBeUndefined(); + }); }); diff --git a/src/extendZodTypes.ts b/src/extendZodTypes.ts index af6e16b..c1762fc 100644 --- a/src/extendZodTypes.ts +++ b/src/extendZodTypes.ts @@ -1,20 +1,22 @@ -import type { ZodDate, ZodObject, ZodTypeAny, z } from 'zod'; +import type { ZodObject, ZodTypeAny, z } from 'zod'; import type { CreationType } from './create/components'; import type { oas30, oas31 } from './openapi3-ts/dist'; type SchemaObject = oas30.SchemaObject & oas31.SchemaObject; +type ReplaceDate = T extends Date ? Date | string : T; + /** * zod-openapi metadata */ interface ZodOpenApiMetadata< T extends ZodTypeAny, - TInferred = z.input | z.output, + TInferred = Exclude | z.output>, undefined>, > extends SchemaObject { example?: TInferred; examples?: [TInferred, ...TInferred[]]; - default?: T extends ZodDate ? string : TInferred; + default?: TInferred; /** * Used to set the output of a ZodUnion to be `oneOf` instead of `allOf` */