Skip to content

Commit 5dd2d62

Browse files
committed
fixed non-compilation example code for myzod
1 parent 163658b commit 5dd2d62

File tree

3 files changed

+42
-43
lines changed

3 files changed

+42
-43
lines changed

codegen.yml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,23 @@ generates:
5757
startsWith: ['regex', '/^$1/', 'message']
5858
format:
5959
email: email
60+
example/myzod/schemas.ts:
61+
plugins:
62+
- ./dist/main/index.js:
63+
schema: myzod
64+
importFrom: ../types
65+
directives:
66+
# Write directives like
67+
#
68+
# directive:
69+
# arg1: schemaApi
70+
# arg2: ["schemaApi2", "Hello $1"]
71+
#
72+
# See more examples in `./tests/directive.spec.ts`
73+
# https://github.com/Code-Hex/graphql-codegen-typescript-validation-schema/blob/main/tests/directive.spec.ts
74+
constraint:
75+
minLength: min
76+
# Replace $1 with specified `startsWith` argument value of the constraint directive
77+
startsWith: ['pattern', '/^$1/']
78+
format:
79+
email: email

src/myzod/index.ts

Lines changed: 7 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import { DeclarationBlock, indent } from '@graphql-codegen/visitor-plugin-common
1212
import { TsVisitor } from '@graphql-codegen/typescript';
1313
import { buildApi, formatDirectiveConfig } from '../directive';
1414

15-
const importZod = `import myzod from 'myzod'`;
15+
const importZod = `import * as myzod from 'myzod'`;
1616
const anySchema = `definedNonNullAnySchema`;
1717

1818
export const MyZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSchemaPluginConfig) => {
@@ -30,32 +30,11 @@ export const MyZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSche
3030
initialEmit: (): string =>
3131
'\n' +
3232
[
33-
/*
34-
* MyZod allows you to create typed objects with `myzod.Type<YourCustomType>`
35-
* See https://www.npmjs.com/package/myzod#lazy
36-
new DeclarationBlock({})
37-
.asKind('type')
38-
.withName('Properties<T>')
39-
.withContent(['Required<{', ' [K in keyof T]: z.ZodType<T[K], any, T[K]>;', '}>'].join('\n')).string,
40-
*/
41-
/*
42-
* MyZod allows empty object hence no need for these hacks
43-
* See https://www.npmjs.com/package/myzod#object
44-
// Unfortunately, zod doesn’t provide non-null defined any schema.
45-
// This is a temporary hack until it is fixed.
46-
// see: https://github.com/colinhacks/zod/issues/884
47-
new DeclarationBlock({}).asKind('type').withName('definedNonNullAny').withContent('{}').string,
48-
new DeclarationBlock({})
49-
.export()
50-
.asKind('const')
51-
.withName(`isDefinedNonNullAny`)
52-
.withContent(`(v: any): v is definedNonNullAny => v !== undefined && v !== null`).string,
5333
new DeclarationBlock({})
5434
.export()
5535
.asKind('const')
5636
.withName(`${anySchema}`)
57-
.withContent(`z.any().refine((v) => isDefinedNonNullAny(v))`).string,
58-
*/
37+
.withContent(`myzod.object({})`).string,
5938
].join('\n'),
6039
InputObjectTypeDefinition: (node: InputObjectTypeDefinitionNode) => {
6140
const name = tsVisitor.convertName(node.name.value);
@@ -67,9 +46,9 @@ export const MyZodSchemaVisitor = (schema: GraphQLSchema, config: ValidationSche
6746

6847
return new DeclarationBlock({})
6948
.export()
70-
.asKind('const')
71-
.withName(`${name}Schema: myzod.Type<${name}>`) //TODO: Test this
72-
.withBlock([indent(`myzod.object({`), shape, indent('})')].join('\n')).string;
49+
.asKind('function')
50+
.withName(`${name}Schema(): myzod.Type<${name}>`)
51+
.withBlock([indent(`return myzod.object({`), shape, indent('})')].join('\n')).string;
7352
},
7453
EnumTypeDefinition: (node: EnumTypeDefinitionNode) => {
7554
const enumname = tsVisitor.convertName(node.name.value);
@@ -177,7 +156,7 @@ const generateNameNodeMyZodSchema = (
177156
return `${enumName}Schema`;
178157
}
179158

180-
return zod4Scalar(config, tsVisitor, node.value);
159+
return myzod4Scalar(config, tsVisitor, node.value);
181160
};
182161

183162
const maybeLazy = (type: TypeNode, schema: string): string => {
@@ -187,7 +166,7 @@ const maybeLazy = (type: TypeNode, schema: string): string => {
187166
return schema;
188167
};
189168

190-
const zod4Scalar = (config: ValidationSchemaPluginConfig, tsVisitor: TsVisitor, scalarName: string): string => {
169+
const myzod4Scalar = (config: ValidationSchemaPluginConfig, tsVisitor: TsVisitor, scalarName: string): string => {
191170
if (config.scalarSchemas?.[scalarName]) {
192171
return config.scalarSchemas[scalarName];
193172
}

tests/myzod.spec.ts

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ describe('myzod', () => {
1515
}
1616
`,
1717
[
18-
'export const PrimitiveInputSchema: myzod.Type<PrimitiveInput>',
18+
'export function PrimitiveInputSchema(): myzod.Type<PrimitiveInput> {',
1919
'a: myzod.string()',
2020
'b: myzod.string()',
2121
'c: myzod.boolean()',
@@ -36,7 +36,7 @@ describe('myzod', () => {
3636
}
3737
`,
3838
[
39-
'export const PrimitiveInputSchema: myzod.Type<PrimitiveInput>',
39+
'export function PrimitiveInputSchema(): myzod.Type<PrimitiveInput> {',
4040
// alphabet order
4141
'a: myzod.string().optional().nullable(),',
4242
'b: myzod.string().optional().nullable(),',
@@ -58,7 +58,7 @@ describe('myzod', () => {
5858
}
5959
`,
6060
[
61-
'export const ArrayInputSchema: myzod.Type<ArrayInput>',
61+
'export function ArrayInputSchema(): myzod.Type<ArrayInput> {',
6262
'a: myzod.array(myzod.string().nullable()).optional().nullable(),',
6363
'b: myzod.array(myzod.string()).optional().nullable(),',
6464
'c: myzod.array(myzod.string()),',
@@ -81,11 +81,11 @@ describe('myzod', () => {
8181
}
8282
`,
8383
[
84-
'export const AInputSchema: myzod.Type<AInput>',
84+
'export function AInputSchema(): myzod.Type<AInput> {',
8585
'b: myzod.lazy(() => BInputSchema())',
86-
'export const BInputSchema: myzod.Type<BInput>',
86+
'export function BInputSchema(): myzod.Type<BInput> {',
8787
'c: myzod.lazy(() => CInputSchema())',
88-
'export const CInputSchema: myzod.Type<CInput>',
88+
'export function CInputSchema(): myzod.Type<CInput> {',
8989
'a: myzod.lazy(() => AInputSchema())',
9090
],
9191
],
@@ -98,7 +98,7 @@ describe('myzod', () => {
9898
}
9999
`,
100100
[
101-
'export const NestedInputSchema: myzod.Type<NestedInput>',
101+
'export function NestedInputSchema(): myzod.Type<NestedInput> {',
102102
'child: myzod.lazy(() => NestedInputSchema().optional().nullable()),',
103103
'childrens: myzod.array(myzod.lazy(() => NestedInputSchema().nullable())).optional().nullable()',
104104
],
@@ -116,7 +116,7 @@ describe('myzod', () => {
116116
`,
117117
[
118118
'export const PageTypeSchema = myzod.enum(PageType)',
119-
'export const PageInputSchema: myzod.Type<PageInput>',
119+
'export function PageInputSchema(): myzod.Type<PageInput> {',
120120
'pageType: PageTypeSchema',
121121
],
122122
],
@@ -136,7 +136,7 @@ describe('myzod', () => {
136136
scalar URL # unknown scalar, should be any (definedNonNullAnySchema)
137137
`,
138138
[
139-
'export const HttpInputSchema: myzod.Type<HttpInput>',
139+
'export function HttpInputSchema(): myzod.Type<HttpInput> {',
140140
'export const HttpMethodSchema = myzod.enum(HttpMethod)',
141141
'method: HttpMethodSchema',
142142
'url: definedNonNullAnySchema',
@@ -145,7 +145,7 @@ describe('myzod', () => {
145145
])('%s', async (_, textSchema, wantContains) => {
146146
const schema = buildSchema(textSchema);
147147
const result = await plugin(schema, [], { schema: 'myzod' }, {});
148-
expect(result.prepend).toContain("import myzod from 'myzod'");
148+
expect(result.prepend).toContain("import * as myzod from 'myzod'");
149149

150150
for (const wantContain of wantContains) {
151151
expect(result.content).toContain(wantContain);
@@ -236,7 +236,7 @@ describe('myzod', () => {
236236
{}
237237
);
238238
const wantContains = [
239-
'export const PrimitiveInputSchema: myzod.Type<PrimitiveInput>',
239+
'export function PrimitiveInputSchema(): myzod.Type<PrimitiveInput> {',
240240
'a: myzod.string().min(1),',
241241
'b: myzod.string().min(1),',
242242
'c: myzod.boolean(),',
@@ -271,7 +271,7 @@ describe('myzod', () => {
271271
{}
272272
);
273273
const wantContains = [
274-
'export const ScalarsInputSchema: myzod.Type<ScalarsInput>',
274+
'export function ScalarsInputSchema(): myzod.Type<ScalarsInput> {',
275275
'date: myzod.date(),',
276276
'email: myzod.string()', // TODO: Test implementation
277277
'str: myzod.string()',
@@ -304,7 +304,7 @@ describe('myzod', () => {
304304
{}
305305
);
306306
const wantContains = [
307-
'export const UserCreateInputSchema: myzod.Type<UserCreateInput>',
307+
'export function UserCreateInputSchema(): myzod.Type<UserCreateInput> {',
308308
'profile: myzod.string().min(1, "Please input more than 1").max(5000, "Please input less than 5000").optional().nullable()',
309309
];
310310
for (const wantContain of wantContains) {
@@ -334,7 +334,7 @@ describe('myzod', () => {
334334
{}
335335
);
336336
const wantContains = [
337-
'export const UserCreateInputSchema: myzod.Type<UserCreateInput>',
337+
'export function UserCreateInputSchema(): myzod.Type<UserCreateInput> {',
338338
'profile: myzod.string().min(1, "Please input more than 1").max(5000, "Please input less than 5000")',
339339
];
340340
for (const wantContain of wantContains) {
@@ -364,7 +364,7 @@ describe('myzod', () => {
364364
{}
365365
);
366366
const wantContains = [
367-
'export const UserCreateInputSchema: myzod.Type<UserCreateInput>',
367+
'export function UserCreateInputSchema(): myzod.Type<UserCreateInput> {',
368368
'profile: myzod.array(myzod.string().nullable()).min(1, "Please input more than 1").max(5000, "Please input less than 5000").optional().nullable()',
369369
];
370370
for (const wantContain of wantContains) {

0 commit comments

Comments
 (0)