Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support ZodBranded, ZodCatch and ZodReadonly in discriminator keys #255

Merged
merged 2 commits into from
Apr 20, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Support new discriminator keys
samchungy committed Apr 20, 2024

Verified

This commit was created on GitHub.com and signed with GitHub’s verified signature.
commit 01803776a7ef0f235adc11dfb19b6f8630474ed7
181 changes: 181 additions & 0 deletions src/create/schema/parsers/discriminatedUnion.test.ts
Original file line number Diff line number Diff line change
@@ -177,4 +177,185 @@ describe('createDiscriminatedUnionSchema', () => {

expect(result).toEqual(expected);
});

it('handles a discriminated union with an optional type', () => {
const expected: Schema = {
type: 'schema',
schema: {
oneOf: [
{
$ref: '#/components/schemas/a',
},
{
$ref: '#/components/schemas/b',
},
],
},
};
const schema = z.discriminatedUnion('type', [
z
.object({
type: z.literal('a').optional(),
})
.openapi({ ref: 'a' }),
z
.object({
type: z.literal('b'),
})
.openapi({ ref: 'b' }),
]);

const result = createDiscriminatedUnionSchema(schema, createOutputState());

expect(result).toEqual(expected);
});

it('handles a discriminated union with a nullable type', () => {
const expected: Schema = {
type: 'schema',
schema: {
oneOf: [
{
$ref: '#/components/schemas/a',
},
{
$ref: '#/components/schemas/b',
},
],
},
};
const schema = z.discriminatedUnion('type', [
z
.object({
type: z.literal('a').nullable(),
})
.openapi({ ref: 'a' }),
z
.object({
type: z.literal('b'),
})
.openapi({ ref: 'b' }),
]);

const result = createDiscriminatedUnionSchema(schema, createOutputState());

expect(result).toEqual(expected);
});

it('handles a discriminated union with a branded type', () => {
const expected: Schema = {
type: 'schema',
schema: {
discriminator: {
mapping: {
a: '#/components/schemas/a',
b: '#/components/schemas/b',
},
propertyName: 'type',
},
oneOf: [
{
$ref: '#/components/schemas/a',
},
{
$ref: '#/components/schemas/b',
},
],
},
};
const schema = z.discriminatedUnion('type', [
z
.object({
type: z.literal('a').brand(),
})
.openapi({ ref: 'a' }),
z
.object({
type: z.literal('b'),
})
.openapi({ ref: 'b' }),
]);

const result = createDiscriminatedUnionSchema(schema, createOutputState());

expect(result).toEqual(expected);
});

it('handles a discriminated union with a readonly type', () => {
const expected: Schema = {
type: 'schema',
schema: {
discriminator: {
mapping: {
a: '#/components/schemas/a',
b: '#/components/schemas/b',
},
propertyName: 'type',
},
oneOf: [
{
$ref: '#/components/schemas/a',
},
{
$ref: '#/components/schemas/b',
},
],
},
};
const schema = z.discriminatedUnion('type', [
z
.object({
type: z.literal('a').readonly(),
})
.openapi({ ref: 'a' }),
z
.object({
type: z.literal('b'),
})
.openapi({ ref: 'b' }),
]);

const result = createDiscriminatedUnionSchema(schema, createOutputState());

expect(result).toEqual(expected);
});

it('handles a discriminated union with a catch type', () => {
const expected: Schema = {
type: 'schema',
schema: {
discriminator: {
mapping: {
a: '#/components/schemas/a',
b: '#/components/schemas/b',
},
propertyName: 'type',
},
oneOf: [
{
$ref: '#/components/schemas/a',
},
{
$ref: '#/components/schemas/b',
},
],
},
};
const schema = z.discriminatedUnion('type', [
z
.object({
type: z.literal('a').catch('a'),
})
.openapi({ ref: 'a' }),
z
.object({
type: z.literal('b'),
})
.openapi({ ref: 'b' }),
]);

const result = createDiscriminatedUnionSchema(schema, createOutputState());

expect(result).toEqual(expected);
});
});
38 changes: 29 additions & 9 deletions src/create/schema/parsers/discriminatedUnion.ts
Original file line number Diff line number Diff line change
@@ -2,8 +2,9 @@ import type {
AnyZodObject,
ZodDiscriminatedUnion,
ZodDiscriminatedUnionOption,
ZodLiteralDef,
ZodRawShape,
ZodType,
ZodTypeAny,
} from 'zod';

import type { oas31 } from '../../../openapi3-ts/dist';
@@ -32,7 +33,6 @@ export const createDiscriminatedUnionSchema = <
schemaObjects,
options,
zodDiscriminatedUnion.discriminator,
state,
);
return {
type: 'schema',
@@ -44,11 +44,35 @@ export const createDiscriminatedUnionSchema = <
};
};

const unwrapLiteral = (
zodType: ZodType | ZodTypeAny | undefined,
): string | undefined => {
if (isZodType(zodType, 'ZodLiteral')) {
if (typeof zodType._def.value !== 'string') {
return undefined;
}
return zodType._def.value;
}

if (isZodType(zodType, 'ZodBranded')) {
return unwrapLiteral(zodType._def.type);
}

if (isZodType(zodType, 'ZodReadonly')) {
return unwrapLiteral(zodType._def.innerType);
}

if (isZodType(zodType, 'ZodCatch')) {
return unwrapLiteral(zodType._def.innerType);
}

return undefined;
};

export const mapDiscriminator = (
schemas: Array<oas31.SchemaObject | oas31.ReferenceObject>,
zodObjects: AnyZodObject[],
discriminator: unknown,
state: SchemaState,
): oas31.SchemaObject['discriminator'] => {
if (typeof discriminator !== 'string') {
return undefined;
@@ -71,14 +95,10 @@ export const mapDiscriminator = (
continue;
}

const literalValue = (value?._def as ZodLiteralDef<unknown>).value;
const literalValue = unwrapLiteral(value);

if (typeof literalValue !== 'string') {
throw new Error(
`Discriminator ${discriminator} could not be found in on index ${index} of a discriminated union at ${state.path.join(
' > ',
)}`,
);
return undefined;
}

mapping[literalValue] = componentSchemaRef;