Skip to content

Input objects support default values #529

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 3 commits into from
Jan 23, 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
15 changes: 14 additions & 1 deletion src/myzod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
GraphQLSchema,
InputObjectTypeDefinitionNode,
InputValueDefinitionNode,
Kind,
NameNode,
ObjectTypeDefinitionNode,
TypeNode,
Expand Down Expand Up @@ -234,7 +235,19 @@ const generateFieldTypeMyZodSchema = (
if (isListType(parentType)) {
return `${gen}.nullable()`;
}
const appliedDirectivesGen = applyDirectives(config, field, gen);
let appliedDirectivesGen = applyDirectives(config, field, gen);

if (field.kind === Kind.INPUT_VALUE_DEFINITION) {
const { defaultValue } = field;

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("${defaultValue.value}")`;
}
}

if (isNonNullType(parentType)) {
if (visitor.shouldEmitAsNotAllowEmptyString(type.name.value)) {
return `${gen}.min(1)`;
Expand Down
39 changes: 27 additions & 12 deletions src/yup/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
GraphQLSchema,
InputObjectTypeDefinitionNode,
InputValueDefinitionNode,
Kind,
NameNode,
ObjectTypeDefinitionNode,
TypeNode,
Expand Down Expand Up @@ -68,12 +69,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
const appendArguments = argumentBlocks ? '\n' + argumentBlocks : '';

// Building schema for fields.
const shape = node.fields
?.map(field => {
const fieldSchema = generateFieldYupSchema(this.config, visitor, field, 2);
return isNonNullType(field.type) ? fieldSchema : `${fieldSchema}.optional()`;
})
.join(',\n');
const shape = shapeFields(node.fields, this.config, visitor)

switch (this.config.validationSchemaExportType) {
case 'const':
Expand Down Expand Up @@ -203,12 +199,7 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
visitor: Visitor,
name: string
) {
const shape = fields
?.map(field => {
const fieldSchema = generateFieldYupSchema(this.config, visitor, field, 2);
return isNonNullType(field.type) ? fieldSchema : `${fieldSchema}.optional()`;
})
.join(',\n');
const shape = shapeFields(fields, this.config, visitor)

switch (this.config.validationSchemaExportType) {
case 'const':
Expand All @@ -229,6 +220,30 @@ export class YupSchemaVisitor extends BaseSchemaVisitor {
}
}

const shapeFields = (fields: readonly (FieldDefinitionNode | InputValueDefinitionNode)[] | undefined, config: ValidationSchemaPluginConfig, visitor: Visitor) => {
return fields?.map(field => {
let fieldSchema = generateFieldYupSchema(config, visitor, field, 2);

if (field.kind === Kind.INPUT_VALUE_DEFINITION) {
const { defaultValue } = field;

if (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("${defaultValue.value}")`;
}
}

if(isNonNullType(field.type)) {
return fieldSchema
}

return `${fieldSchema}.optional()`;
})
.join(',\n');
}

const generateFieldYupSchema = (
config: ValidationSchemaPluginConfig,
visitor: Visitor,
Expand Down
33 changes: 23 additions & 10 deletions src/zod/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
GraphQLSchema,
InputObjectTypeDefinitionNode,
InputValueDefinitionNode,
Kind,
NameNode,
ObjectTypeDefinitionNode,
TypeNode,
Expand Down Expand Up @@ -129,16 +130,16 @@ export class ZodSchemaVisitor extends BaseSchemaVisitor {
this.enumDeclarations.push(
this.config.enumsAsTypes
? new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${enumname}Schema`)
.withContent(`z.enum([${node.values?.map(enumOption => `'${enumOption.name.value}'`).join(', ')}])`)
.string
.export()
.asKind('const')
.withName(`${enumname}Schema`)
.withContent(`z.enum([${node.values?.map(enumOption => `'${enumOption.name.value}'`).join(', ')}])`)
.string
: new DeclarationBlock({})
.export()
.asKind('const')
.withName(`${enumname}Schema`)
.withContent(`z.nativeEnum(${enumname})`).string
.export()
.asKind('const')
.withName(`${enumname}Schema`)
.withContent(`z.nativeEnum(${enumname})`).string
);
},
};
Expand Down Expand Up @@ -247,7 +248,19 @@ const generateFieldTypeZodSchema = (
if (isListType(parentType)) {
return `${gen}.nullable()`;
}
const appliedDirectivesGen = applyDirectives(config, field, gen);
let appliedDirectivesGen = applyDirectives(config, field, gen);

if (field.kind === Kind.INPUT_VALUE_DEFINITION) {
const { defaultValue } = field;

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("${defaultValue.value}")`;
}
}

if (isNonNullType(parentType)) {
if (visitor.shouldEmitAsNotAllowEmptyString(type.name.value)) {
return `${appliedDirectivesGen}.min(1)`;
Expand Down
34 changes: 34 additions & 0 deletions tests/myzod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -991,4 +991,38 @@ describe('myzod', () => {
}`;
expect(result.content).toContain(wantContain);
});

it('with default input values', 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',
},
{}
);

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("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()');
});
});
34 changes: 34 additions & 0 deletions tests/yup.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -905,4 +905,38 @@ describe('yup', () => {
}`;
expect(result.content).toContain(wantContain);
});

it('with default input values', 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',
},
{}
);

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

expect(result.content).toContain('pageType: PageTypeSchema.nonNullable().default("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()');
});
});
34 changes: 34 additions & 0 deletions tests/zod.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,40 @@ describe('zod', () => {
expect(result.content).toContain('export function SayISchema(): z.ZodObject<Properties<SayI>> {');
});

it('with default input values', 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',
},
{}
);

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("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()');
});

describe('issues #19', () => {
it('string field', async () => {
const schema = buildSchema(/* GraphQL */ `
Expand Down