Skip to content

V0.4.1 feature myzod #27

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 4 commits into from
Apr 2, 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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"@typescript-eslint/parser": "^5.10.0",
"eslint": "^8.7.0",
"jest": "^27.4.7",
"myzod": "^1.8.7",
"npm-run-all": "^4.1.5",
"prettier": "2.5.1",
"ts-jest": "^27.1.3",
Expand Down
2 changes: 1 addition & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { TypeScriptPluginConfig } from '@graphql-codegen/typescript';

export type ValidationSchema = 'yup' | 'zod';
export type ValidationSchema = 'yup' | 'zod' | 'myzod';

export interface DirectiveConfig {
[directive: string]: {
Expand Down
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ZodSchemaVisitor } from './zod/index';
import { MyZodSchemaVisitor } from './myzod/index';
import { transformSchemaAST } from '@graphql-codegen/schema-ast';
import { YupSchemaVisitor } from './yup/index';
import { ValidationSchemaPluginConfig } from './config';
Expand Down Expand Up @@ -30,6 +31,8 @@ export const plugin: PluginFunction<ValidationSchemaPluginConfig, Types.ComplexP
const schemaVisitor = (schema: GraphQLSchema, config: ValidationSchemaPluginConfig) => {
if (config?.schema === 'zod') {
return ZodSchemaVisitor(schema, config);
} else if (config?.schema === 'myzod') {
return MyZodSchemaVisitor(schema, config);
}
return YupSchemaVisitor(schema, config);
};
205 changes: 205 additions & 0 deletions src/myzod/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import { isInput, isNonNullType, isListType, isNamedType } from './../graphql';
import { ValidationSchemaPluginConfig } from '../config';
import {
InputValueDefinitionNode,
NameNode,
TypeNode,
GraphQLSchema,
InputObjectTypeDefinitionNode,
EnumTypeDefinitionNode,
} from 'graphql';
import { DeclarationBlock, indent } from '@graphql-codegen/visitor-plugin-common';
import { TsVisitor } from '@graphql-codegen/typescript';
import { buildApi, formatDirectiveConfig } from '../directive';

const importZod = `import myzod from 'myzod'`;
const anySchema = `definedNonNullAnySchema`;

export const MyZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSchemaPluginConfig) => {
const tsVisitor = new TsVisitor(schema, config);

const importTypes: string[] = [];

return {
buildImports: (): string[] => {
if (config.importFrom && importTypes.length > 0) {
return [importZod, `import { ${importTypes.join(', ')} } from '${config.importFrom}'`];
}
return [importZod];
},
initialEmit: (): string =>
'\n' +
[
/*
* MyZod allows you to create typed objects with `myzod.Type<YourCustomType>`
* See https://www.npmjs.com/package/myzod#lazy
new DeclarationBlock({})
.asKind('type')
.withName('Properties<T>')
.withContent(['Required<{', ' [K in keyof T]: z.ZodType<T[K], any, T[K]>;', '}>'].join('\n')).string,
*/
/*
* MyZod allows empty object hence no need for these hacks
* See https://www.npmjs.com/package/myzod#object
// Unfortunately, zod doesn’t provide non-null defined any schema.
// This is a temporary hack until it is fixed.
// see: https://github.com/colinhacks/zod/issues/884
new DeclarationBlock({}).asKind('type').withName('definedNonNullAny').withContent('{}').string,
new DeclarationBlock({})
.export()
.asKind('const')
.withName(`isDefinedNonNullAny`)
.withContent(`(v: any): v is definedNonNullAny => v !== undefined && v !== null`).string,
new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${anySchema}`)
.withContent(`z.any().refine((v) => isDefinedNonNullAny(v))`).string,
*/
].join('\n'),
InputObjectTypeDefinition: (node: InputObjectTypeDefinitionNode) => {
const name = tsVisitor.convertName(node.name.value);
importTypes.push(name);

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

return new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${name}Schema: myzod.Type<${name}>`) //TODO: Test this
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you tell me what do you want to test it? I will handle this.

.withBlock([indent(`myzod.object({`), shape, indent('})')].join('\n')).string;
},
EnumTypeDefinition: (node: EnumTypeDefinitionNode) => {
const enumname = tsVisitor.convertName(node.name.value);
importTypes.push(enumname);
// z.enum are basically myzod.literals
if (config.enumsAsTypes) {
return new DeclarationBlock({})
.export()
.asKind('type')
.withName(`${enumname}Schema`)
.withContent(`myzod.literals(${node.values?.map(enumOption => `'${enumOption.name.value}'`).join(', ')})`)
.string;
}

return new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${enumname}Schema`)
.withContent(`myzod.enum(${enumname})`).string;
},
};
};

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

const generateInputObjectFieldTypeMyZodSchema = (
config: ValidationSchemaPluginConfig,
tsVisitor: TsVisitor,
schema: GraphQLSchema,
field: InputValueDefinitionNode,
type: TypeNode,
parentType?: TypeNode
): string => {
if (isListType(type)) {
const gen = generateInputObjectFieldTypeMyZodSchema(config, tsVisitor, schema, field, type.type, type);
if (!isNonNullType(parentType)) {
const arrayGen = `myzod.array(${maybeLazy(type.type, gen)})`;
const maybeLazyGen = applyDirectives(config, field, arrayGen);
return `${maybeLazyGen}.optional().nullable()`;
}
return `myzod.array(${maybeLazy(type.type, gen)})`;
}
if (isNonNullType(type)) {
const gen = generateInputObjectFieldTypeMyZodSchema(config, tsVisitor, schema, field, type.type, type);
return maybeLazy(type.type, gen);
}
if (isNamedType(type)) {
const gen = generateNameNodeMyZodSchema(config, tsVisitor, schema, type.name);
if (isListType(parentType)) {
return `${gen}.nullable()`;
}
const appliedDirectivesGen = applyDirectives(config, field, gen);
if (isNonNullType(parentType)) {
if (config.notAllowEmptyString === true) {
const tsType = tsVisitor.scalars[type.name.value];
if (tsType === 'string') return `${gen}.min(1)`;
}
return appliedDirectivesGen;
}
if (isListType(parentType)) {
return `${appliedDirectivesGen}.nullable()`;
}
return `${appliedDirectivesGen}.optional().nullable()`;
}
console.warn('unhandled type:', type);
return '';
};

const applyDirectives = (
config: ValidationSchemaPluginConfig,
field: InputValueDefinitionNode,
gen: string
): string => {
if (config.directives && field.directives) {
const formatted = formatDirectiveConfig(config.directives);
return gen + buildApi(formatted, field.directives);
}
return gen;
};

const generateNameNodeMyZodSchema = (
config: ValidationSchemaPluginConfig,
tsVisitor: TsVisitor,
schema: GraphQLSchema,
node: NameNode
): string => {
const typ = schema.getType(node.value);

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

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

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

const maybeLazy = (type: TypeNode, schema: string): string => {
if (isNamedType(type) && isInput(type.name.value)) {
return `myzod.lazy(() => ${schema})`;
}
return schema;
};

const zod4Scalar = (config: ValidationSchemaPluginConfig, tsVisitor: TsVisitor, scalarName: string): string => {
if (config.scalarSchemas?.[scalarName]) {
return config.scalarSchemas[scalarName];
}
const tsType = tsVisitor.scalars[scalarName];
switch (tsType) {
case 'string':
return `myzod.string()`;
case 'number':
return `myzod.number()`;
case 'boolean':
return `myzod.boolean()`;
}
console.warn('unhandled name:', scalarName);
return anySchema;
};
4 changes: 2 additions & 2 deletions src/zod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export const ZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSchema
importTypes.push(name);

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

return new DeclarationBlock({})
Expand Down Expand Up @@ -84,7 +84,7 @@ export const ZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSchema
};
};

const generateInputObjectFieldYupSchema = (
const generateInputObjectFieldZodSchema = (
config: ValidationSchemaPluginConfig,
tsVisitor: TsVisitor,
schema: GraphQLSchema,
Expand Down
Loading