Skip to content

implement for variables #453

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 3 commits into from
Aug 13, 2023
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
18 changes: 17 additions & 1 deletion example/myzod/schemas.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as myzod from 'myzod'
import { Admin, AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, Guest, HttpInput, HttpMethod, LayoutInput, PageInput, PageType, User } from '../types'
import { Admin, AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, Guest, HttpInput, HttpMethod, LayoutInput, MyType, MyTypeFooArgs, PageInput, PageType, User } from '../types'

export const definedNonNullAnySchema = myzod.object({});

Expand Down Expand Up @@ -76,6 +76,22 @@ export function LayoutInputSchema(): myzod.Type<LayoutInput> {
})
}

export function MyTypeSchema(): myzod.Type<MyType> {
return myzod.object({
__typename: myzod.literal('MyType').optional(),
foo: myzod.string().optional().nullable()
})
}

export function MyTypeFooArgsSchema(): myzod.Type<MyTypeFooArgs> {
return myzod.object({
a: myzod.string().optional().nullable(),
b: myzod.number(),
c: myzod.boolean().optional().nullable(),
d: myzod.number()
})
}

export function PageInputSchema(): myzod.Type<PageInput> {
return myzod.object({
attributes: myzod.array(myzod.lazy(() => AttributeInputSchema())).optional().nullable(),
Expand Down
4 changes: 4 additions & 0 deletions example/test.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,10 @@ enum HTTPMethod {
scalar Date
scalar URL

type MyType {
foo(a: String, b: Int!, c: Boolean, d: Float!): String
}

# https://github.com/confuser/graphql-constraint-directive
directive @constraint(
# String constraints
Expand Down
13 changes: 13 additions & 0 deletions example/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,19 @@ export type LayoutInput = {
dropdown?: InputMaybe<DropDownComponentInput>;
};

export type MyType = {
__typename?: 'MyType';
foo?: Maybe<Scalars['String']['output']>;
};


export type MyTypeFooArgs = {
a?: InputMaybe<Scalars['String']['input']>;
b: Scalars['Int']['input'];
c?: InputMaybe<Scalars['Boolean']['input']>;
d: Scalars['Float']['input'];
};

export type PageInput = {
attributes?: InputMaybe<Array<AttributeInput>>;
date?: InputMaybe<Scalars['Date']['input']>;
Expand Down
18 changes: 17 additions & 1 deletion example/yup/schemas.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as yup from 'yup'
import { Admin, AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, Guest, HttpInput, HttpMethod, LayoutInput, PageInput, PageType, User, UserKind } from '../types'
import { Admin, AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, Guest, HttpInput, HttpMethod, LayoutInput, MyType, MyTypeFooArgs, PageInput, PageType, User, UserKind } from '../types'

export const ButtonComponentTypeSchema = yup.string<ButtonComponentType>().oneOf([ButtonComponentType.Button, ButtonComponentType.Submit]).defined();

Expand Down Expand Up @@ -80,6 +80,22 @@ export function LayoutInputSchema(): yup.ObjectSchema<LayoutInput> {
})
}

export function MyTypeSchema(): yup.ObjectSchema<MyType> {
return yup.object({
__typename: yup.string<'MyType'>().optional(),
foo: yup.string().defined().nullable().optional()
})
}

export function MyTypeFooArgsSchema(): yup.ObjectSchema<MyTypeFooArgs> {
return yup.object({
a: yup.string().defined().nullable(),
b: yup.number().defined().nonNullable(),
c: yup.boolean().defined().nullable(),
d: yup.number().defined().nonNullable()
})
}

export function PageInputSchema(): yup.ObjectSchema<PageInput> {
return yup.object({
attributes: yup.array(yup.lazy(() => AttributeInputSchema().nonNullable())).defined().nullable().optional(),
Expand Down
18 changes: 17 additions & 1 deletion example/zod/schemas.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { z } from 'zod'
import { Admin, AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, Guest, HttpInput, HttpMethod, LayoutInput, PageInput, PageType, User } from '../types'
import { Admin, AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, Guest, HttpInput, HttpMethod, LayoutInput, MyType, MyTypeFooArgs, PageInput, PageType, User } from '../types'

type Properties<T> = Required<{
[K in keyof T]: z.ZodType<T[K], any, T[K]>;
Expand Down Expand Up @@ -84,6 +84,22 @@ export function LayoutInputSchema(): z.ZodObject<Properties<LayoutInput>> {
})
}

export function MyTypeSchema(): z.ZodObject<Properties<MyType>> {
return z.object({
__typename: z.literal('MyType').optional(),
foo: z.string().nullish()
})
}

export function MyTypeFooArgsSchema(): z.ZodObject<Properties<MyTypeFooArgs>> {
return z.object({
a: z.string().nullish(),
b: z.number(),
c: z.boolean().nullish(),
d: z.number()
})
}

export function PageInputSchema(): z.ZodObject<Properties<PageInput>> {
return z.object({
attributes: z.array(z.lazy(() => AttributeInputSchema())).nullish(),
Expand Down
77 changes: 53 additions & 24 deletions src/myzod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,37 +73,66 @@ export const MyZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSche
const name = visitor.convertName(node.name.value);
importTypes.push(name);

// Building schema for field arguments.
const argumentBlocks = visitor.buildArgumentsSchemaBlock(node, (typeName, field) => {
importTypes.push(typeName);
const args = field.arguments ?? [];
const shape = args.map(field => generateFieldMyZodSchema(config, visitor, field, 2)).join(',\n');
switch (config.validationSchemaExportType) {
case 'const':
return new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${typeName}Schema: myzod.Type<${typeName}>`)
.withContent([`myzod.object({`, shape, '})'].join('\n')).string;

case 'function':
default:
return new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${typeName}Schema(): myzod.Type<${typeName}>`)
.withBlock([indent(`return myzod.object({`), shape, indent('})')].join('\n')).string;
}
});
const appendArguments = argumentBlocks ? '\n' + argumentBlocks : '';

// Building schema for fields.
const shape = node.fields?.map(field => generateFieldMyZodSchema(config, visitor, field, 2)).join(',\n');

switch (config.validationSchemaExportType) {
case 'const':
return new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${name}Schema: myzod.Type<${name}>`)
.withContent(
[
`myzod.object({`,
indent(`__typename: myzod.literal('${node.name.value}').optional(),`, 2),
shape,
'})',
].join('\n')
).string;
return (
new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${name}Schema: myzod.Type<${name}>`)
.withContent(
[
`myzod.object({`,
indent(`__typename: myzod.literal('${node.name.value}').optional(),`, 2),
shape,
'})',
].join('\n')
).string + appendArguments
);

case 'function':
default:
return new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): myzod.Type<${name}>`)
.withBlock(
[
indent(`return myzod.object({`),
indent(`__typename: myzod.literal('${node.name.value}').optional(),`, 2),
shape,
indent('})'),
].join('\n')
).string;
return (
new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): myzod.Type<${name}>`)
.withBlock(
[
indent(`return myzod.object({`),
indent(`__typename: myzod.literal('${node.name.value}').optional(),`, 2),
shape,
indent('})'),
].join('\n')
).string + appendArguments
);
}
}),
},
Expand Down
26 changes: 25 additions & 1 deletion src/visitor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { TsVisitor } from '@graphql-codegen/typescript';
import { GraphQLSchema, NameNode, specifiedScalarTypes } from 'graphql';
import { FieldDefinitionNode, GraphQLSchema, NameNode, ObjectTypeDefinitionNode, specifiedScalarTypes } from 'graphql';

import { ValidationSchemaPluginConfig } from './config';

Expand Down Expand Up @@ -50,4 +50,28 @@ export class Visitor extends TsVisitor {
const tsType = this.getScalarType(name);
return tsType === 'string';
}

public buildArgumentsSchemaBlock(
node: ObjectTypeDefinitionNode,
callback: (typeName: string, field: FieldDefinitionNode) => string
) {
const fieldsWithArguments = node.fields?.filter(field => field.arguments && field.arguments.length > 0) ?? [];
if (fieldsWithArguments.length === 0) {
return undefined;
}
return fieldsWithArguments
.map(field => {
const name =
node.name.value +
(this.config.addUnderscoreToArgsType ? '_' : '') +
this.convertName(field, {
useTypesPrefix: false,
useTypesSuffix: false,
}) +
'Args';

return callback(name, field);
})
.join('\n');
}
}
78 changes: 54 additions & 24 deletions src/yup/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,32 @@ export const YupSchemaVisitor = (schema: GraphQLSchema, config: ValidationSchema
const name = visitor.convertName(node.name.value);
importTypes.push(name);

// Building schema for field arguments.
const argumentBlocks = visitor.buildArgumentsSchemaBlock(node, (typeName, field) => {
importTypes.push(typeName);
const args = field.arguments ?? [];
const shape = args.map(field => generateFieldYupSchema(config, visitor, field, 2)).join(',\n');
switch (config.validationSchemaExportType) {
case 'const':
return new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${typeName}Schema: yup.ObjectSchema<${typeName}>`)
.withContent([`yup.object({`, shape, '})'].join('\n')).string;

case 'function':
default:
return new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${typeName}Schema(): yup.ObjectSchema<${typeName}>`)
.withBlock([indent(`return yup.object({`), shape, indent('})')].join('\n')).string;
}
});
const appendArguments = argumentBlocks ? '\n' + argumentBlocks : '';

// Building schema for fields.

const shape = node.fields
?.map(field => {
const fieldSchema = generateFieldYupSchema(config, visitor, field, 2);
Expand All @@ -97,33 +123,37 @@ export const YupSchemaVisitor = (schema: GraphQLSchema, config: ValidationSchema

switch (config.validationSchemaExportType) {
case 'const':
return new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${name}Schema: yup.ObjectSchema<${name}>`)
.withContent(
[
`yup.object({`,
indent(`__typename: yup.string<'${node.name.value}'>().optional(),`, 2),
shape,
'})',
].join('\n')
).string;
return (
new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${name}Schema: yup.ObjectSchema<${name}>`)
.withContent(
[
`yup.object({`,
indent(`__typename: yup.string<'${node.name.value}'>().optional(),`, 2),
shape,
'})',
].join('\n')
).string + appendArguments
);

case 'function':
default:
return new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): yup.ObjectSchema<${name}>`)
.withBlock(
[
indent(`return yup.object({`),
indent(`__typename: yup.string<'${node.name.value}'>().optional(),`, 2),
shape,
indent('})'),
].join('\n')
).string;
return (
new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): yup.ObjectSchema<${name}>`)
.withBlock(
[
indent(`return yup.object({`),
indent(`__typename: yup.string<'${node.name.value}'>().optional(),`, 2),
shape,
indent('})'),
].join('\n')
).string + appendArguments
);
}
}),
},
Expand Down
Loading