Skip to content

Commit 36ef007

Browse files
Add support for union in myzod
Co-authored-by: alexandruluca <[email protected]>
1 parent a30764a commit 36ef007

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

src/myzod/index.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
ObjectTypeDefinitionNode,
1010
EnumTypeDefinitionNode,
1111
FieldDefinitionNode,
12+
UnionTypeDefinitionNode,
1213
} from 'graphql';
1314
import { DeclarationBlock, indent } from '@graphql-codegen/visitor-plugin-common';
1415
import { TsVisitor } from '@graphql-codegen/typescript';
@@ -89,6 +90,18 @@ export const MyZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSche
8990
.withName(`${enumname}Schema`)
9091
.withContent(`myzod.enum(${enumname})`).string;
9192
},
93+
UnionTypeDefinition: (node: UnionTypeDefinitionNode) => {
94+
const unionName = tsVisitor.convertName(node.name.value);
95+
const unionElements = node.types?.map(t => `${t.name.value}Schema()`).join(', ');
96+
97+
const result = new DeclarationBlock({})
98+
.export()
99+
.asKind('function')
100+
.withName(`${unionName}Schema()`)
101+
.withBlock(indent(`return myzod.union([${unionElements}])`));
102+
103+
return result.string;
104+
},
92105
};
93106
};
94107

tests/myzod.spec.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,38 @@ describe('myzod', () => {
538538
expect(result.content).not.toContain(wantNotContain);
539539
}
540540
});
541+
542+
it('generate union types', async () => {
543+
const schema = buildSchema(/* GraphQL */ `
544+
type Square {
545+
size: Int
546+
}
547+
type Circle {
548+
radius: Int
549+
}
550+
union Shape = Circle | Square
551+
`);
552+
553+
const result = await plugin(
554+
schema,
555+
[],
556+
{
557+
schema: 'myzod',
558+
withObjectType: true,
559+
},
560+
{}
561+
);
562+
563+
const wantContains = [
564+
// Shape Schema
565+
'export function ShapeSchema() {',
566+
'myzod.union([CircleSchema(), SquareSchema()])',
567+
'}',
568+
];
569+
for (const wantContain of wantContains) {
570+
expect(result.content).toContain(wantContain);
571+
}
572+
});
541573
});
542574

543575
it('properly generates custom directive values', async () => {

tests/zod.spec.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -662,6 +662,7 @@ describe('zod', () => {
662662
// Shape Schema
663663
'export function ShapeSchema() {',
664664
'z.union([CircleSchema(), SquareSchema()])',
665+
'}',
665666
];
666667
for (const wantContain of wantContains) {
667668
expect(result.content).toContain(wantContain);

0 commit comments

Comments
 (0)