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

Adding GraphQL type support to codegen - with test #132

Merged
merged 2 commits into from
Jul 29, 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
3 changes: 3 additions & 0 deletions codegen.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ generates:
- ./dist/main/index.js:
schema: yup
importFrom: ../types
useObjectTypes: true
directives:
required:
msg: required
Expand Down Expand Up @@ -42,6 +43,7 @@ generates:
- ./dist/main/index.js:
schema: zod
importFrom: ../types
useObjectTypes: true
directives:
# Write directives like
#
Expand All @@ -62,6 +64,7 @@ generates:
- ./dist/main/index.js:
schema: myzod
importFrom: ../types
useObjectTypes: true
directives:
constraint:
minLength: min
Expand Down
14 changes: 13 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 { AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, HttpInput, HttpMethod, LayoutInput, PageInput, PageType } from '../types'
import { AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, HttpInput, HttpMethod, LayoutInput, PageInput, PageType, User } from '../types'

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

Expand Down Expand Up @@ -77,3 +77,15 @@ export function PageInputSchema(): myzod.Type<PageInput> {
}

export const PageTypeSchema = myzod.enum(PageType);

export function UserSchema(): myzod.Type<User> {
return myzod.object({
__typename: myzod.literal('User').optional(),
createdAt: definedNonNullAnySchema.optional().nullable(),
email: myzod.string().optional().nullable(),
id: myzod.string().optional().nullable(),
name: myzod.string().optional().nullable(),
password: myzod.string().optional().nullable(),
updatedAt: definedNonNullAnySchema.optional().nullable()
})
}
9 changes: 9 additions & 0 deletions example/test.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ enum PageType {
BASIC_AUTH
}

type User {
id: ID
name: String
email: String
password: String
createdAt: Date
updatedAt: Date
}

input PageInput {
id: ID!
title: String!
Expand Down
10 changes: 10 additions & 0 deletions example/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,3 +86,13 @@ export enum PageType {
Restricted = 'RESTRICTED',
Service = 'SERVICE'
}

export type User = {
__typename?: 'User';
createdAt?: Maybe<Scalars['Date']>;
email?: Maybe<Scalars['String']>;
id?: Maybe<Scalars['ID']>;
name?: Maybe<Scalars['String']>;
password?: Maybe<Scalars['String']>;
updatedAt?: Maybe<Scalars['Date']>;
};
14 changes: 13 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 { AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, HttpInput, HttpMethod, LayoutInput, PageInput, PageType } from '../types'
import { AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, HttpInput, HttpMethod, LayoutInput, PageInput, PageType, User } from '../types'

export function AttributeInputSchema(): yup.SchemaOf<AttributeInput> {
return yup.object({
Expand Down Expand Up @@ -75,3 +75,15 @@ export function PageInputSchema(): yup.SchemaOf<PageInput> {
}

export const PageTypeSchema = yup.mixed().oneOf([PageType.BasicAuth, PageType.Lp, PageType.Restricted, PageType.Service]);

export function UserSchema(): yup.SchemaOf<User> {
return yup.object({
__typename: yup.mixed().oneOf(['User', undefined]),
createdAt: yup.mixed(),
email: yup.string(),
id: yup.string(),
name: yup.string(),
password: yup.string(),
updatedAt: yup.mixed()
})
}
14 changes: 13 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 { AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, HttpInput, HttpMethod, LayoutInput, PageInput, PageType } from '../types'
import { AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, HttpInput, HttpMethod, LayoutInput, PageInput, PageType, User } from '../types'

type Properties<T> = Required<{
[K in keyof T]: z.ZodType<T[K], any, T[K]>;
Expand Down Expand Up @@ -85,3 +85,15 @@ export function PageInputSchema(): z.ZodObject<Properties<PageInput>> {
}

export const PageTypeSchema = z.nativeEnum(PageType);

export function UserSchema(): z.ZodObject<Properties<User>> {
return z.object({
__typename: z.literal('User').optional(),
createdAt: definedNonNullAnySchema.nullish(),
email: z.string().nullish(),
id: z.string().nullish(),
name: z.string().nullish(),
password: z.string().nullish(),
updatedAt: definedNonNullAnySchema.nullish()
})
}
20 changes: 19 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export interface ValidationSchemaPluginConfig extends TypeScriptPluginConfig {
* @description import types from generated typescript type path
* if not given, omit import statement.
*
* @exampeMarkdown
* @exampleMarkdown
* ```yml
* generates:
* path/to/types.ts:
Expand Down Expand Up @@ -193,4 +193,22 @@ export interface ValidationSchemaPluginConfig extends TypeScriptPluginConfig {
* ```
*/
directives?: DirectiveConfig;
/**
* @description Converts the regular graphql type into a zod validation function.
*
* @exampleMarkdown
* ```yml
* generates:
* path/to/types.ts:
* plugins:
* - typescript
* path/to/schemas.ts:
* plugins:
* - graphql-codegen-validation-schema
* config:
* schema: yup
* useObjectTypes: true
* ```
*/
useObjectTypes?: boolean;
}
41 changes: 32 additions & 9 deletions src/myzod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import {
TypeNode,
GraphQLSchema,
InputObjectTypeDefinitionNode,
ObjectTypeDefinitionNode,
EnumTypeDefinitionNode,
FieldDefinitionNode,
} from 'graphql';
import { DeclarationBlock, indent } from '@graphql-codegen/visitor-plugin-common';
import { TsVisitor } from '@graphql-codegen/typescript';
Expand Down Expand Up @@ -38,7 +40,7 @@ export const MyZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSche
importTypes.push(name);

const shape = node.fields
?.map(field => generateInputObjectFieldMyZodSchema(config, tsVisitor, schema, field, 2))
?.map(field => generateFieldMyZodSchema(config, tsVisitor, schema, field, 2))
.join(',\n');

return new DeclarationBlock({})
Expand All @@ -47,6 +49,27 @@ export const MyZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSche
.withName(`${name}Schema(): myzod.Type<${name}>`)
.withBlock([indent(`return myzod.object({`), shape, indent('})')].join('\n')).string;
},
ObjectTypeDefinition: (node: ObjectTypeDefinitionNode) => {
if (!config.useObjectTypes) return;
const name = tsVisitor.convertName(node.name.value);
importTypes.push(name);

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

return new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): myzod.Type<${name}>`)
.withBlock(
[
indent(`return myzod.object({`),
` __typename: myzod.literal('${node.name.value}').optional(),\n${shape}`,
indent('})'),
].join('\n')
).string;
},
EnumTypeDefinition: (node: EnumTypeDefinitionNode) => {
const enumname = tsVisitor.convertName(node.name.value);
importTypes.push(enumname);
Expand All @@ -69,27 +92,27 @@ export const MyZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSche
};
};

const generateInputObjectFieldMyZodSchema = (
const generateFieldMyZodSchema = (
config: ValidationSchemaPluginConfig,
tsVisitor: TsVisitor,
schema: GraphQLSchema,
field: InputValueDefinitionNode,
field: InputValueDefinitionNode | FieldDefinitionNode,
indentCount: number
): string => {
const gen = generateInputObjectFieldTypeMyZodSchema(config, tsVisitor, schema, field, field.type);
const gen = generateFieldTypeMyZodSchema(config, tsVisitor, schema, field, field.type);
return indent(`${field.name.value}: ${maybeLazy(field.type, gen)}`, indentCount);
};

const generateInputObjectFieldTypeMyZodSchema = (
const generateFieldTypeMyZodSchema = (
config: ValidationSchemaPluginConfig,
tsVisitor: TsVisitor,
schema: GraphQLSchema,
field: InputValueDefinitionNode,
field: InputValueDefinitionNode | FieldDefinitionNode,
type: TypeNode,
parentType?: TypeNode
): string => {
if (isListType(type)) {
const gen = generateInputObjectFieldTypeMyZodSchema(config, tsVisitor, schema, field, type.type, type);
const gen = generateFieldTypeMyZodSchema(config, tsVisitor, schema, field, type.type, type);
if (!isNonNullType(parentType)) {
const arrayGen = `myzod.array(${maybeLazy(type.type, gen)})`;
const maybeLazyGen = applyDirectives(config, field, arrayGen);
Expand All @@ -98,7 +121,7 @@ const generateInputObjectFieldTypeMyZodSchema = (
return `myzod.array(${maybeLazy(type.type, gen)})`;
}
if (isNonNullType(type)) {
const gen = generateInputObjectFieldTypeMyZodSchema(config, tsVisitor, schema, field, type.type, type);
const gen = generateFieldTypeMyZodSchema(config, tsVisitor, schema, field, type.type, type);
return maybeLazy(type.type, gen);
}
if (isNamedType(type)) {
Expand All @@ -125,7 +148,7 @@ const generateInputObjectFieldTypeMyZodSchema = (

const applyDirectives = (
config: ValidationSchemaPluginConfig,
field: InputValueDefinitionNode,
field: InputValueDefinitionNode | FieldDefinitionNode,
gen: string
): string => {
if (config.directives && field.directives) {
Expand Down
37 changes: 28 additions & 9 deletions src/yup/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import {
GraphQLSchema,
InputObjectTypeDefinitionNode,
EnumTypeDefinitionNode,
ObjectTypeDefinitionNode,
FieldDefinitionNode,
} from 'graphql';
import { DeclarationBlock, indent } from '@graphql-codegen/visitor-plugin-common';
import { TsVisitor } from '@graphql-codegen/typescript';
Expand All @@ -31,16 +33,33 @@ export const YupSchemaVisitor = (schema: GraphQLSchema, config: ValidationSchema
const name = tsVisitor.convertName(node.name.value);
importTypes.push(name);

const shape = node.fields
?.map(field => generateInputObjectFieldYupSchema(config, tsVisitor, schema, field, 2))
.join(',\n');
const shape = node.fields?.map(field => generateFieldYupSchema(config, tsVisitor, schema, field, 2)).join(',\n');

return new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): yup.SchemaOf<${name}>`)
.withBlock([indent(`return yup.object({`), shape, indent('})')].join('\n')).string;
},
ObjectTypeDefinition: (node: ObjectTypeDefinitionNode) => {
if (!config.useObjectTypes) return;
const name = tsVisitor.convertName(node.name.value);
importTypes.push(name);

const shape = node.fields?.map(field => generateFieldYupSchema(config, tsVisitor, schema, field, 2)).join(',\n');

return new DeclarationBlock({})
.export()
.asKind('function')
.withName(`${name}Schema(): yup.SchemaOf<${name}>`)
.withBlock(
[
indent(`return yup.object({`),
` __typename: yup.mixed().oneOf(['${node.name.value}', undefined]),\n${shape}`,
indent('})'),
].join('\n')
).string;
},
EnumTypeDefinition: (node: EnumTypeDefinitionNode) => {
const enumname = tsVisitor.convertName(node.name.value);
importTypes.push(enumname);
Expand Down Expand Up @@ -92,37 +111,37 @@ export const YupSchemaVisitor = (schema: GraphQLSchema, config: ValidationSchema
};
};

const generateInputObjectFieldYupSchema = (
const generateFieldYupSchema = (
config: ValidationSchemaPluginConfig,
tsVisitor: TsVisitor,
schema: GraphQLSchema,
field: InputValueDefinitionNode,
field: InputValueDefinitionNode | FieldDefinitionNode,
indentCount: number
): string => {
let gen = generateInputObjectFieldTypeYupSchema(config, tsVisitor, schema, field.type);
let gen = generateFieldTypeYupSchema(config, tsVisitor, schema, field.type);
if (config.directives && field.directives) {
const formatted = formatDirectiveConfig(config.directives);
gen += buildApi(formatted, field.directives);
}
return indent(`${field.name.value}: ${maybeLazy(field.type, gen)}`, indentCount);
};

const generateInputObjectFieldTypeYupSchema = (
const generateFieldTypeYupSchema = (
config: ValidationSchemaPluginConfig,
tsVisitor: TsVisitor,
schema: GraphQLSchema,
type: TypeNode,
parentType?: TypeNode
): string => {
if (isListType(type)) {
const gen = generateInputObjectFieldTypeYupSchema(config, tsVisitor, schema, type.type, type);
const gen = generateFieldTypeYupSchema(config, tsVisitor, schema, type.type, type);
if (!isNonNullType(parentType)) {
return `yup.array().of(${maybeLazy(type.type, gen)}).optional()`;
}
return `yup.array().of(${maybeLazy(type.type, gen)})`;
}
if (isNonNullType(type)) {
const gen = generateInputObjectFieldTypeYupSchema(config, tsVisitor, schema, type.type, type);
const gen = generateFieldTypeYupSchema(config, tsVisitor, schema, type.type, type);
const nonNullGen = maybeNonEmptyString(config, tsVisitor, gen, type.type);
return maybeLazy(type.type, nonNullGen);
}
Expand Down
Loading