Skip to content

Moist feat/enum type as default value #723

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
Jul 7, 2024
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
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.
Copy link

Choose a reason for hiding this comment

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

I think there is a "typo" here, this is the same description as the previous configuration knob.

Copy link
Owner Author

Choose a reason for hiding this comment

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

@mat813 Could you send me a PR to fix this?

Copy link
Contributor

Choose a reason for hiding this comment

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

@mat813 it's not a typo, it's a prop within the delta.

* @default { enumValues: "change-case-all#pascalCase" }
*
* 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
18 changes: 15 additions & 3 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 @@ -284,8 +285,19 @@ function shapeFields(fields: readonly (FieldDefinitionNode | InputValueDefinitio
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