Skip to content

Support union types for zod generator #237

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

Merged
merged 5 commits into from
Nov 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
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
22 changes: 22 additions & 0 deletions src/myzod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
ObjectTypeDefinitionNode,
EnumTypeDefinitionNode,
FieldDefinitionNode,
UnionTypeDefinitionNode,
} from 'graphql';
import { DeclarationBlock, indent } from '@graphql-codegen/visitor-plugin-common';
import { TsVisitor } from '@graphql-codegen/typescript';
Expand Down Expand Up @@ -89,6 +90,22 @@ export const MyZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSche
.withName(`${enumname}Schema`)
.withContent(`myzod.enum(${enumname})`).string;
},
UnionTypeDefinition: (node: UnionTypeDefinitionNode) => {
const unionName = tsVisitor.convertName(node.name.value);
const unionElements = node.types?.map(t => `${tsVisitor.convertName(t.name.value)}Schema()`).join(', ');
const unionElementsCount = node.types?.length ?? 0;

const union =
unionElementsCount > 1 ? indent(`return myzod.union([${unionElements}])`) : indent(`return ${unionElements}`);

const result = new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${unionName}Schema()`)
.withBlock(union);

return result.string;
},
};
};

Expand Down Expand Up @@ -181,6 +198,11 @@ const generateNameNodeMyZodSchema = (
return `${enumName}Schema`;
}

if (typ?.astNode?.kind === 'UnionTypeDefinition') {
const enumName = tsVisitor.convertName(typ.astNode.name.value);
return `${enumName}Schema()`;
}

return myzod4Scalar(config, tsVisitor, node.value);
};

Expand Down
31 changes: 30 additions & 1 deletion src/yup/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
EnumTypeDefinitionNode,
ObjectTypeDefinitionNode,
FieldDefinitionNode,
UnionTypeDefinitionNode,
} from 'graphql';
import { DeclarationBlock, indent } from '@graphql-codegen/visitor-plugin-common';
import { TsVisitor } from '@graphql-codegen/typescript';
Expand All @@ -28,7 +29,17 @@ export const YupSchemaVisitor = (schema: GraphQLSchema, config: ValidationSchema
}
return [importYup];
},
initialEmit: (): string => '',
initialEmit: (): string =>
new DeclarationBlock({})
.asKind('function')
.withName('union<T>(...schemas: ReadonlyArray<yup.SchemaOf<T>>): yup.BaseSchema<T>')
.withBlock(
[
indent('return yup.mixed().test({'),
indent('test: (value) => schemas.some((schema) => schema.isValidSync(value))', 2),
indent('})'),
].join('\n')
).string,
InputObjectTypeDefinition: (node: InputObjectTypeDefinitionNode) => {
const name = tsVisitor.convertName(node.name.value);
importTypes.push(name);
Expand Down Expand Up @@ -89,6 +100,24 @@ export const YupSchemaVisitor = (schema: GraphQLSchema, config: ValidationSchema
.withName(`${enumname}Schema`)
.withContent(`yup.mixed().oneOf([${values}])`).string;
},
UnionTypeDefinition: (node: UnionTypeDefinitionNode) => {
const unionName = tsVisitor.convertName(node.name.value);
const unionElements = node.types?.map(t => `${tsVisitor.convertName(t.name.value)}Schema()`).join(', ');
const unionElementsCount = node.types?.length ?? 0;

const union =
unionElementsCount > 1
? indent(`return union<${unionName}>(${unionElements})`)
: indent(`return ${unionElements}`);

const result = new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${unionName}Schema(): yup.BaseSchema<${unionName}>`)
.withBlock(union);

return result.string;
},
// ScalarTypeDefinition: (node) => {
// const decl = new DeclarationBlock({})
// .export()
Expand Down
22 changes: 22 additions & 0 deletions src/zod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
InputObjectTypeDefinitionNode,
ObjectTypeDefinitionNode,
EnumTypeDefinitionNode,
UnionTypeDefinitionNode,
FieldDefinitionNode,
} from 'graphql';
import { DeclarationBlock, indent } from '@graphql-codegen/visitor-plugin-common';
Expand Down Expand Up @@ -100,6 +101,22 @@ export const ZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSchema
.withName(`${enumname}Schema`)
.withContent(`z.nativeEnum(${enumname})`).string;
},
UnionTypeDefinition: (node: UnionTypeDefinitionNode) => {
const unionName = tsVisitor.convertName(node.name.value);
const unionElements = node.types?.map(t => `${tsVisitor.convertName(t.name.value)}Schema()`).join(', ');
const unionElementsCount = node.types?.length ?? 0;

const union =
unionElementsCount > 1 ? indent(`return z.union([${unionElements}])`) : indent(`return ${unionElements}`);

const result = new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${unionName}Schema()`)
.withBlock(union);

return result.string;
},
};
};

Expand Down Expand Up @@ -192,6 +209,11 @@ const generateNameNodeZodSchema = (
return `${enumName}Schema`;
}

if (typ?.astNode?.kind === 'UnionTypeDefinition') {
const enumName = tsVisitor.convertName(typ.astNode.name.value);
return `${enumName}Schema()`;
}

return zod4Scalar(config, tsVisitor, node.value);
};

Expand Down
98 changes: 98 additions & 0 deletions tests/myzod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,104 @@ describe('myzod', () => {
expect(result.content).not.toContain(wantNotContain);
}
});

it('generate union types', async () => {
const schema = buildSchema(/* GraphQL */ `
type Square {
size: Int
}
type Circle {
radius: Int
}
union Shape = Circle | Square
`);

const result = await plugin(
schema,
[],
{
schema: 'myzod',
withObjectType: true,
},
{}
);

const wantContains = [
// Shape Schema
'export function ShapeSchema() {',
'myzod.union([CircleSchema(), SquareSchema()])',
'}',
];
for (const wantContain of wantContains) {
expect(result.content).toContain(wantContain);
}
});

it('generate union types with single element', async () => {
const schema = buildSchema(/* GraphQL */ `
type Square {
size: Int
}
type Circle {
radius: Int
}
union Shape = Circle | Square

type Geometry {
shape: Shape
}
`);

const result = await plugin(
schema,
[],
{
schema: 'myzod',
withObjectType: true,
},
{}
);

const wantContains = [
'export function GeometrySchema(): myzod.Type<Geometry> {',
'return myzod.object({',
"__typename: myzod.literal('Geometry').optional(),",
'shape: ShapeSchema().optional().nullable()',
'}',
];
for (const wantContain of wantContains) {
expect(result.content).toContain(wantContain);
}
});

it('correctly reference generated union types', async () => {
const schema = buildSchema(/* GraphQL */ `
type Circle {
radius: Int
}
union Shape = Circle
`);

const result = await plugin(
schema,
[],
{
schema: 'myzod',
withObjectType: true,
},
{}
);

const wantContains = [
// Shape Schema
'export function ShapeSchema() {',
'CircleSchema()',
'}',
];
for (const wantContain of wantContains) {
expect(result.content).toContain(wantContain);
}
});
});

it('properly generates custom directive values', async () => {
Expand Down
98 changes: 98 additions & 0 deletions tests/yup.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,6 +451,104 @@ describe('yup', () => {
expect(result.content).not.toContain(wantNotContain);
}
});

it('generate union types', async () => {
const schema = buildSchema(/* GraphQL */ `
type Square {
size: Int
}
type Circle {
radius: Int
}
union Shape = Circle | Square
`);

const result = await plugin(
schema,
[],
{
schema: 'yup',
withObjectType: true,
},
{}
);

const wantContains = [
// Shape Schema
'export function ShapeSchema(): yup.BaseSchema<Shape> {',
'union<Shape>(CircleSchema(), SquareSchema())',
'}',
];
for (const wantContain of wantContains) {
expect(result.content).toContain(wantContain);
}
});

it('generate union types with single element', async () => {
const schema = buildSchema(/* GraphQL */ `
type Square {
size: Int
}
type Circle {
radius: Int
}
union Shape = Circle | Square

type Geometry {
shape: Shape
}
`);

const result = await plugin(
schema,
[],
{
schema: 'yup',
withObjectType: true,
},
{}
);

const wantContains = [
'export function GeometrySchema(): yup.SchemaOf<Geometry> {',
'return yup.object({',
"__typename: yup.mixed().oneOf(['Geometry', undefined]),",
'shape: yup.mixed()',
'})',
];
for (const wantContain of wantContains) {
expect(result.content).toContain(wantContain);
}
});

it('correctly reference generated union types', async () => {
const schema = buildSchema(/* GraphQL */ `
type Circle {
radius: Int
}
union Shape = Circle
`);

const result = await plugin(
schema,
[],
{
schema: 'yup',
withObjectType: true,
},
{}
);

const wantContains = [
// Shape Schema
'export function ShapeSchema(): yup.BaseSchema<Shape> {',
'CircleSchema()',
'}',
];
for (const wantContain of wantContains) {
expect(result.content).toContain(wantContain);
}
});
});

it('properly generates custom directive values', async () => {
Expand Down
Loading