Skip to content

fix(default-value): add flag to utilize generated enum types for default values #636

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

Closed
Closed
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,591 changes: 1,491 additions & 2,100 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

37 changes: 37 additions & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { TypeScriptPluginConfig } from '@graphql-codegen/typescript';
import type { NamingConventionMap } from '@graphql-codegen/visitor-plugin-common';

export type ValidationSchema = 'yup' | 'zod' | 'myzod' | 'valibot';
export type ValidationSchemaExportType = 'function' | 'const';
Expand Down Expand Up @@ -210,6 +211,42 @@ export interface ValidationSchemaPluginConfig extends TypeScriptPluginConfig {
* ```
*/
validationSchemaExportType?: ValidationSchemaExportType
/**
* @description Uses the full path of the enum type as the default value instead of the stringified value.
* @default false
*
* @exampleMarkdown
* ```yml
* generates:
* path/to/file.ts:
* plugins:
* - typescript
* - graphql-codegen-validation-schema
* config:
* useEnumTypeAsDefault: true
* ```
*/
useEnumTypeAsDefaultValue?: boolean
/**
* @description Uses the full path of the enum type as the default value instead of the stringified value.
* @default { enumValues: "change-case-all#pascalCase" }
Copy link
Owner

Choose a reason for hiding this comment

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

I don't know how to use it with just this, so I think it's better to describe the URL using @link
https://the-guild.dev/graphql/codegen/docs/config-reference/naming-convention

JSDoc: https://jsdoc.app/tags-inline-link

Btw, I think it would be confusing if the user uses transformUnderscore or typeNames as this feature is not applicable. is it possible to support transformUnderscore and typeNames? or write a comment?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@Code-Hex I don't believe that Valibot supports default values for enum/"picklist" types at the moment, it seems like a new library. I don't see anything on the documentation https://valibot.dev/guides/enums/ around enums/"picklists" supporting default values, nor the API for enums: https://valibot.dev/api/enum/

I'll disregard Valibot for now, as it's not possible.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@Code-Hex I've also added a comment for transformUnderscore and typeNames.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@Code-Hex I've rebased against main and this is ready for review now.

Copy link
Owner

Choose a reason for hiding this comment

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

@sutt0n Thanks! I agree ignore Valibot for now.
I'm sorry, but could you please add what you added to your comment in the README? I'll merge it once, so if you could make a PR for me, that would be great!

*
* Note: This option has not been tested with `namingConvention.transformUnderscore` and `namingConvention.typeNames` options,
* and may not work as expected.
*
* @exampleMarkdown
* ```yml
* generates:
* path/to/file.ts:
* plugins:
* - typescript
* - graphql-codegen-validation-schema
* config:
* namingConvention:
* enumValues: change-case-all#pascalCase
* ```
*/
namingConvention?: NamingConventionMap
/**
* @description Generates validation schema with more API based on directive schema.
* @exampleMarkdown
Expand Down
18 changes: 15 additions & 3 deletions src/myzod/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DeclarationBlock, indent } from '@graphql-codegen/visitor-plugin-common';
import { DeclarationBlock, convertNameParts, indent } from '@graphql-codegen/visitor-plugin-common';
import type {
EnumTypeDefinitionNode,
FieldDefinitionNode,
Expand All @@ -15,6 +15,7 @@ import {
Kind,
} from 'graphql';

import { resolveExternalModuleAndFn } from '@graphql-codegen/plugin-helpers';
import type { ValidationSchemaPluginConfig } from '../config';
import { buildApi, formatDirectiveConfig } from '../directive';
import { BaseSchemaVisitor } from '../schema_visitor';
Expand Down Expand Up @@ -282,8 +283,19 @@ function generateFieldTypeMyZodSchema(config: ValidationSchemaPluginConfig, visi
if (defaultValue?.kind === Kind.INT || defaultValue?.kind === Kind.FLOAT || defaultValue?.kind === Kind.BOOLEAN)
appliedDirectivesGen = `${appliedDirectivesGen}.default(${defaultValue.value})`;

if (defaultValue?.kind === Kind.STRING || defaultValue?.kind === Kind.ENUM)
appliedDirectivesGen = `${appliedDirectivesGen}.default("${escapeGraphQLCharacters(defaultValue.value)}")`;
if (defaultValue?.kind === Kind.STRING || defaultValue?.kind === Kind.ENUM) {
if (config.useEnumTypeAsDefaultValue && defaultValue?.kind !== Kind.STRING) {
let value = convertNameParts(defaultValue.value, resolveExternalModuleAndFn('change-case-all#pascalCase'));

if (config.namingConvention?.enumValues)
value = convertNameParts(defaultValue.value, resolveExternalModuleAndFn(config.namingConvention?.enumValues));

appliedDirectivesGen = `${appliedDirectivesGen}.default(${visitor.convertName(type.name.value)}.${value})`;
}
else {
appliedDirectivesGen = `${appliedDirectivesGen}.default("${escapeGraphQLCharacters(defaultValue.value)}")`;
}
}
}

if (isNonNullType(parentType)) {
Expand Down
4 changes: 2 additions & 2 deletions src/valibot/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,9 +205,9 @@ function generateFieldTypeValibotSchema(config: ValidationSchemaPluginConfig, vi
if (isListType(type)) {
const gen = generateFieldTypeValibotSchema(config, visitor, field, type.type, type);
const arrayGen = `v.array(${maybeLazy(type.type, gen)})`;
if (!isNonNullType(parentType)) {
if (!isNonNullType(parentType))
return `v.nullish(${arrayGen})`;
}

return arrayGen;
}
if (isNonNullType(type)) {
Expand Down
21 changes: 16 additions & 5 deletions src/yup/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DeclarationBlock, indent } from '@graphql-codegen/visitor-plugin-common';
import { DeclarationBlock, convertNameParts, indent } from '@graphql-codegen/visitor-plugin-common';
import type {
EnumTypeDefinitionNode,
FieldDefinitionNode,
Expand All @@ -15,6 +15,7 @@ import {
Kind,
} from 'graphql';

import { resolveExternalModuleAndFn } from '@graphql-codegen/plugin-helpers';
import type { ValidationSchemaPluginConfig } from '../config';
import { buildApi, formatDirectiveConfig } from '../directive';
import { BaseSchemaVisitor } from '../schema_visitor';
Expand Down Expand Up @@ -280,12 +281,22 @@ function shapeFields(fields: readonly (FieldDefinitionNode | InputValueDefinitio
defaultValue?.kind === Kind.INT
|| defaultValue?.kind === Kind.FLOAT
|| defaultValue?.kind === Kind.BOOLEAN
) {
)
fieldSchema = `${fieldSchema}.default(${defaultValue.value})`;
}

if (defaultValue?.kind === Kind.STRING || defaultValue?.kind === Kind.ENUM)
fieldSchema = `${fieldSchema}.default("${escapeGraphQLCharacters(defaultValue.value)}")`;
if (defaultValue?.kind === Kind.STRING || defaultValue?.kind === Kind.ENUM) {
if (config.useEnumTypeAsDefaultValue && defaultValue?.kind !== Kind.STRING) {
let value = convertNameParts(defaultValue.value, resolveExternalModuleAndFn('change-case-all#pascalCase'));

if (config.namingConvention?.enumValues)
value = convertNameParts(defaultValue.value, resolveExternalModuleAndFn(config.namingConvention?.enumValues));

fieldSchema = `${fieldSchema}.default(${visitor.convertName(field.name.value)}.${value})`;
}
else {
fieldSchema = `${fieldSchema}.default("${escapeGraphQLCharacters(defaultValue.value)}")`;
}
}
}

if (isNonNullType(field.type))
Expand Down
18 changes: 15 additions & 3 deletions src/zod/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DeclarationBlock, indent } from '@graphql-codegen/visitor-plugin-common';
import { DeclarationBlock, convertNameParts, indent } from '@graphql-codegen/visitor-plugin-common';
import type {
EnumTypeDefinitionNode,
FieldDefinitionNode,
Expand All @@ -15,6 +15,7 @@ import {
Kind,
} from 'graphql';

import { resolveExternalModuleAndFn } from '@graphql-codegen/plugin-helpers';
import type { ValidationSchemaPluginConfig } from '../config';
import { buildApi, formatDirectiveConfig } from '../directive';
import { BaseSchemaVisitor } from '../schema_visitor';
Expand Down Expand Up @@ -295,8 +296,19 @@ function generateFieldTypeZodSchema(config: ValidationSchemaPluginConfig, visito
if (defaultValue?.kind === Kind.INT || defaultValue?.kind === Kind.FLOAT || defaultValue?.kind === Kind.BOOLEAN)
appliedDirectivesGen = `${appliedDirectivesGen}.default(${defaultValue.value})`;

if (defaultValue?.kind === Kind.STRING || defaultValue?.kind === Kind.ENUM)
appliedDirectivesGen = `${appliedDirectivesGen}.default("${escapeGraphQLCharacters(defaultValue.value)}")`;
if (defaultValue?.kind === Kind.STRING || defaultValue?.kind === Kind.ENUM) {
if (config.useEnumTypeAsDefaultValue && defaultValue?.kind !== Kind.STRING) {
let value = convertNameParts(defaultValue.value, resolveExternalModuleAndFn('change-case-all#pascalCase'));

if (config.namingConvention?.enumValues)
value = convertNameParts(defaultValue.value, resolveExternalModuleAndFn(config.namingConvention?.enumValues));

appliedDirectivesGen = `${appliedDirectivesGen}.default(${type.name.value}.${value})`;
}
else {
appliedDirectivesGen = `${appliedDirectivesGen}.default("${escapeGraphQLCharacters(defaultValue.value)}")`;
}
}
}

if (isNonNullType(parentType)) {
Expand Down
35 changes: 35 additions & 0 deletions tests/myzod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1409,4 +1409,39 @@ describe('myzod', () => {
"
`)
});

it('with default input values as enum types', async () => {
const schema = buildSchema(/* GraphQL */ `
enum PageType {
PUBLIC
BASIC_AUTH
}
input PageInput {
pageType: PageType! = PUBLIC
greeting: String = "Hello"
score: Int = 100
ratio: Float = 0.5
isMember: Boolean = true
}
`);
const result = await plugin(
schema,
[],
{
schema: 'myzod',
importFrom: './types',
useEnumTypeAsDefaultValue: true,
},
{},
);

expect(result.content).toContain('export const PageTypeSchema = myzod.enum(PageType)');
expect(result.content).toContain('export function PageInputSchema(): myzod.Type<PageInput>');

expect(result.content).toContain('pageType: PageTypeSchema.default(PageType.Public)');
expect(result.content).toContain('greeting: myzod.string().default("Hello").optional().nullable()');
expect(result.content).toContain('score: myzod.number().default(100).optional().nullable()');
expect(result.content).toContain('ratio: myzod.number().default(0.5).optional().nullable()');
expect(result.content).toContain('isMember: myzod.boolean().default(true).optional().nullable()');
});
});
37 changes: 37 additions & 0 deletions tests/yup.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1433,4 +1433,41 @@ describe('yup', () => {
"
`)
});

it('with default input values as enum types', async () => {
const schema = buildSchema(/* GraphQL */ `
enum PageType {
PUBLIC
BASIC_AUTH
}
input PageInput {
pageType: PageType! = PUBLIC
greeting: String = "Hello"
score: Int = 100
ratio: Float = 0.5
isMember: Boolean = true
}
`);
const result = await plugin(
schema,
[],
{
schema: 'yup',
importFrom: './types',
useEnumTypeAsDefaultValue: true,
},
{},
);

expect(result.content).toContain(
'export const PageTypeSchema = yup.string<PageType>().oneOf(Object.values(PageType)).defined()',
);
expect(result.content).toContain('export function PageInputSchema(): yup.ObjectSchema<PageInput>');

expect(result.content).toContain('pageType: PageTypeSchema.nonNullable().default(PageType.Public)');
expect(result.content).toContain('greeting: yup.string().defined().nullable().default("Hello").optional()');
expect(result.content).toContain('score: yup.number().defined().nullable().default(100).optional()');
expect(result.content).toContain('ratio: yup.number().defined().nullable().default(0.5).optional()');
expect(result.content).toContain('isMember: yup.boolean().defined().nullable().default(true).optional()');
});
});
36 changes: 36 additions & 0 deletions tests/zod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,42 @@ describe('zod', () => {
`)
});

it('with default input values as enum types', async () => {
const schema = buildSchema(/* GraphQL */ `
enum PageType {
PUBLIC
BASIC_AUTH
}
input PageInput {
pageType: PageType! = PUBLIC
greeting: String = "Hello"
score: Int = 100
ratio: Float = 0.5
isMember: Boolean = true
}
`);
const result = await plugin(
schema,
[],
{
schema: 'zod',
importFrom: './types',
useEnumTypeAsDefaultValue: true,
},
{
},
);

expect(result.content).toContain('export const PageTypeSchema = z.nativeEnum(PageType)');
expect(result.content).toContain('export function PageInputSchema(): z.ZodObject<Properties<PageInput>>');

expect(result.content).toContain('pageType: PageTypeSchema.default(PageType.Public)');
expect(result.content).toContain('greeting: z.string().default("Hello").nullish()');
expect(result.content).toContain('score: z.number().default(100).nullish()');
expect(result.content).toContain('ratio: z.number().default(0.5).nullish()');
expect(result.content).toContain('isMember: z.boolean().default(true).nullish()');
});

it('with default input values', async () => {
const schema = buildSchema(/* GraphQL */ `
enum PageType {
Expand Down
Loading