Skip to content

fixed non-compilation example code for myzod #28

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
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

- [x] support [yup](https://github.com/jquense/yup)
- [x] support [zod](https://github.com/colinhacks/zod)
- [x] support [myzod](https://github.com/davidmdm/myzod)

## Quick Start

Expand All @@ -29,9 +30,9 @@ generates:
schema: yup # or zod
```

You can check [example directory](https://github.com/Code-Hex/graphql-codegen-typescript-validation-schema/tree/main/example) if you want to see more complex config example or how is generated some files.
You can check [example](https://github.com/Code-Hex/graphql-codegen-typescript-validation-schema/tree/main/example) directory if you want to see more complex config example or how is generated some files.

...And I wrote some tips in there.
The Q&A for each schema is written in the README in the respective example directory.

## Config API Reference

Expand All @@ -41,7 +42,7 @@ type: `ValidationSchema` default: `'yup'`

Specify generete validation schema you want.

You can specify `yup` or `zod`.
You can specify `yup` or `zod` or `myzod`.

```yml
generates:
Expand Down Expand Up @@ -207,3 +208,7 @@ export function ExampleInputSchema(): z.ZodSchema<ExampleInput> {
})
}
```

#### other schema

Please see [example](https://github.com/Code-Hex/graphql-codegen-typescript-validation-schema/tree/main/example) directory.
12 changes: 12 additions & 0 deletions codegen.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,15 @@ generates:
startsWith: ['regex', '/^$1/', 'message']
format:
email: email
example/myzod/schemas.ts:
plugins:
- ./dist/main/index.js:
schema: myzod
importFrom: ../types
directives:
constraint:
minLength: min
# Replace $1 with specified `startsWith` argument value of the constraint directive
startsWith: ['pattern', '/^$1/']
format:
email: email
7 changes: 7 additions & 0 deletions example/myzod/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Tips for myzod schema

## How to overwrite generated schema?

Basically, I think [it does not support overwrite schema](https://github.com/davidmdm/myzod/issues/51) in myzod. However, [`and`](https://github.com/davidmdm/myzod#typeand) and [`or`](https://github.com/davidmdm/myzod#typeor) may helps you.

See also: https://github.com/Code-Hex/graphql-codegen-typescript-validation-schema/issues/25#issuecomment-1086532098
79 changes: 79 additions & 0 deletions example/myzod/schemas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import * as myzod from 'myzod'
import { AttributeInput, ButtonComponentType, ComponentInput, DropDownComponentInput, EventArgumentInput, EventInput, EventOptionType, HttpInput, HttpMethod, LayoutInput, PageInput, PageType } from '../types'

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

export function AttributeInputSchema(): myzod.Type<AttributeInput> {
return myzod.object({
key: myzod.string().optional().nullable(),
val: myzod.string().optional().nullable()
})
}

export const ButtonComponentTypeSchema = myzod.enum(ButtonComponentType);

export function ComponentInputSchema(): myzod.Type<ComponentInput> {
return myzod.object({
child: myzod.lazy(() => ComponentInputSchema().optional().nullable()),
childrens: myzod.array(myzod.lazy(() => ComponentInputSchema().nullable())).optional().nullable(),
event: myzod.lazy(() => EventInputSchema().optional().nullable()),
name: myzod.string(),
type: ButtonComponentTypeSchema
})
}

export function DropDownComponentInputSchema(): myzod.Type<DropDownComponentInput> {
return myzod.object({
dropdownComponent: myzod.lazy(() => ComponentInputSchema().optional().nullable()),
getEvent: myzod.lazy(() => EventInputSchema())
})
}

export function EventArgumentInputSchema(): myzod.Type<EventArgumentInput> {
return myzod.object({
name: myzod.string().min(5),
value: myzod.string().pattern(/^foo/)
})
}

export function EventInputSchema(): myzod.Type<EventInput> {
return myzod.object({
arguments: myzod.array(myzod.lazy(() => EventArgumentInputSchema())),
options: myzod.array(EventOptionTypeSchema).optional().nullable()
})
}

export const EventOptionTypeSchema = myzod.enum(EventOptionType);

export function HttpInputSchema(): myzod.Type<HttpInput> {
return myzod.object({
method: HttpMethodSchema.optional().nullable(),
url: definedNonNullAnySchema
})
}

export const HttpMethodSchema = myzod.enum(HttpMethod);

export function LayoutInputSchema(): myzod.Type<LayoutInput> {
return myzod.object({
dropdown: myzod.lazy(() => DropDownComponentInputSchema().optional().nullable())
})
}

export function PageInputSchema(): myzod.Type<PageInput> {
return myzod.object({
attributes: myzod.array(myzod.lazy(() => AttributeInputSchema())).optional().nullable(),
date: definedNonNullAnySchema.optional().nullable(),
height: myzod.number(),
id: myzod.string(),
layout: myzod.lazy(() => LayoutInputSchema()),
pageType: PageTypeSchema,
postIDs: myzod.array(myzod.string()).optional().nullable(),
show: myzod.boolean(),
tags: myzod.array(myzod.string().nullable()).optional().nullable(),
title: myzod.string(),
width: myzod.number()
})
}

export const PageTypeSchema = myzod.enum(PageType);
40 changes: 8 additions & 32 deletions src/myzod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ 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 importZod = `import * as myzod from 'myzod'`;
const anySchema = `definedNonNullAnySchema`;

export const MyZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSchemaPluginConfig) => {
Expand All @@ -30,32 +30,8 @@ export const MyZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSche
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,
*/
new DeclarationBlock({}).export().asKind('const').withName(`${anySchema}`).withContent(`myzod.object({})`)
.string,
].join('\n'),
InputObjectTypeDefinition: (node: InputObjectTypeDefinitionNode) => {
const name = tsVisitor.convertName(node.name.value);
Expand All @@ -67,9 +43,9 @@ export const MyZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSche

return new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${name}Schema: myzod.Type<${name}>`) //TODO: Test this
.withBlock([indent(`myzod.object({`), shape, indent('})')].join('\n')).string;
.asKind('function')
.withName(`${name}Schema(): myzod.Type<${name}>`)
.withBlock([indent(`return myzod.object({`), shape, indent('})')].join('\n')).string;
},
EnumTypeDefinition: (node: EnumTypeDefinitionNode) => {
const enumname = tsVisitor.convertName(node.name.value);
Expand Down Expand Up @@ -177,7 +153,7 @@ const generateNameNodeMyZodSchema = (
return `${enumName}Schema`;
}

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

const maybeLazy = (type: TypeNode, schema: string): string => {
Expand All @@ -187,7 +163,7 @@ const maybeLazy = (type: TypeNode, schema: string): string => {
return schema;
};

const zod4Scalar = (config: ValidationSchemaPluginConfig, tsVisitor: TsVisitor, scalarName: string): string => {
const myzod4Scalar = (config: ValidationSchemaPluginConfig, tsVisitor: TsVisitor, scalarName: string): string => {
if (config.scalarSchemas?.[scalarName]) {
return config.scalarSchemas[scalarName];
}
Expand Down
30 changes: 15 additions & 15 deletions tests/myzod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ describe('myzod', () => {
}
`,
[
'export const PrimitiveInputSchema: myzod.Type<PrimitiveInput>',
'export function PrimitiveInputSchema(): myzod.Type<PrimitiveInput> {',
'a: myzod.string()',
'b: myzod.string()',
'c: myzod.boolean()',
Expand All @@ -36,7 +36,7 @@ describe('myzod', () => {
}
`,
[
'export const PrimitiveInputSchema: myzod.Type<PrimitiveInput>',
'export function PrimitiveInputSchema(): myzod.Type<PrimitiveInput> {',
// alphabet order
'a: myzod.string().optional().nullable(),',
'b: myzod.string().optional().nullable(),',
Expand All @@ -58,7 +58,7 @@ describe('myzod', () => {
}
`,
[
'export const ArrayInputSchema: myzod.Type<ArrayInput>',
'export function ArrayInputSchema(): myzod.Type<ArrayInput> {',
'a: myzod.array(myzod.string().nullable()).optional().nullable(),',
'b: myzod.array(myzod.string()).optional().nullable(),',
'c: myzod.array(myzod.string()),',
Expand All @@ -81,11 +81,11 @@ describe('myzod', () => {
}
`,
[
'export const AInputSchema: myzod.Type<AInput>',
'export function AInputSchema(): myzod.Type<AInput> {',
'b: myzod.lazy(() => BInputSchema())',
'export const BInputSchema: myzod.Type<BInput>',
'export function BInputSchema(): myzod.Type<BInput> {',
'c: myzod.lazy(() => CInputSchema())',
'export const CInputSchema: myzod.Type<CInput>',
'export function CInputSchema(): myzod.Type<CInput> {',
'a: myzod.lazy(() => AInputSchema())',
],
],
Expand All @@ -98,7 +98,7 @@ describe('myzod', () => {
}
`,
[
'export const NestedInputSchema: myzod.Type<NestedInput>',
'export function NestedInputSchema(): myzod.Type<NestedInput> {',
'child: myzod.lazy(() => NestedInputSchema().optional().nullable()),',
'childrens: myzod.array(myzod.lazy(() => NestedInputSchema().nullable())).optional().nullable()',
],
Expand All @@ -116,7 +116,7 @@ describe('myzod', () => {
`,
[
'export const PageTypeSchema = myzod.enum(PageType)',
'export const PageInputSchema: myzod.Type<PageInput>',
'export function PageInputSchema(): myzod.Type<PageInput> {',
'pageType: PageTypeSchema',
],
],
Expand All @@ -136,7 +136,7 @@ describe('myzod', () => {
scalar URL # unknown scalar, should be any (definedNonNullAnySchema)
`,
[
'export const HttpInputSchema: myzod.Type<HttpInput>',
'export function HttpInputSchema(): myzod.Type<HttpInput> {',
'export const HttpMethodSchema = myzod.enum(HttpMethod)',
'method: HttpMethodSchema',
'url: definedNonNullAnySchema',
Expand All @@ -145,7 +145,7 @@ describe('myzod', () => {
])('%s', async (_, textSchema, wantContains) => {
const schema = buildSchema(textSchema);
const result = await plugin(schema, [], { schema: 'myzod' }, {});
expect(result.prepend).toContain("import myzod from 'myzod'");
expect(result.prepend).toContain("import * as myzod from 'myzod'");

for (const wantContain of wantContains) {
expect(result.content).toContain(wantContain);
Expand Down Expand Up @@ -236,7 +236,7 @@ describe('myzod', () => {
{}
);
const wantContains = [
'export const PrimitiveInputSchema: myzod.Type<PrimitiveInput>',
'export function PrimitiveInputSchema(): myzod.Type<PrimitiveInput> {',
'a: myzod.string().min(1),',
'b: myzod.string().min(1),',
'c: myzod.boolean(),',
Expand Down Expand Up @@ -271,7 +271,7 @@ describe('myzod', () => {
{}
);
const wantContains = [
'export const ScalarsInputSchema: myzod.Type<ScalarsInput>',
'export function ScalarsInputSchema(): myzod.Type<ScalarsInput> {',
'date: myzod.date(),',
'email: myzod.string()', // TODO: Test implementation
'str: myzod.string()',
Expand Down Expand Up @@ -304,7 +304,7 @@ describe('myzod', () => {
{}
);
const wantContains = [
'export const UserCreateInputSchema: myzod.Type<UserCreateInput>',
'export function UserCreateInputSchema(): myzod.Type<UserCreateInput> {',
'profile: myzod.string().min(1, "Please input more than 1").max(5000, "Please input less than 5000").optional().nullable()',
];
for (const wantContain of wantContains) {
Expand Down Expand Up @@ -334,7 +334,7 @@ describe('myzod', () => {
{}
);
const wantContains = [
'export const UserCreateInputSchema: myzod.Type<UserCreateInput>',
'export function UserCreateInputSchema(): myzod.Type<UserCreateInput> {',
'profile: myzod.string().min(1, "Please input more than 1").max(5000, "Please input less than 5000")',
];
for (const wantContain of wantContains) {
Expand Down Expand Up @@ -364,7 +364,7 @@ describe('myzod', () => {
{}
);
const wantContains = [
'export const UserCreateInputSchema: myzod.Type<UserCreateInput>',
'export function UserCreateInputSchema(): myzod.Type<UserCreateInput> {',
'profile: myzod.array(myzod.string().nullable()).min(1, "Please input more than 1").max(5000, "Please input less than 5000").optional().nullable()',
];
for (const wantContain of wantContains) {
Expand Down