Skip to content

fix(zod): Required fields with a default value should be optional in Typed JSON cases #2044

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 1 commit into from
Mar 18, 2025
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
12 changes: 7 additions & 5 deletions packages/schema/src/plugins/zod/transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,22 +282,24 @@ export default class Transformer {

const fieldName = alternatives.some((alt) => alt.includes(':')) ? '' : ` ${field.name}:`;

const opt = !field.isRequired ? '.optional()' : '';

let resString: string;

if (alternatives.length === 1) {
resString = alternatives.join(',\r\n');
resString = alternatives[0];
} else {
if (alternatives.some((alt) => alt.includes('Unchecked'))) {
// if the union is for combining checked and unchecked input types, use `smartUnion`
// to parse with the best candidate at runtime
resString = this.wrapWithSmartUnion(...alternatives) + `${opt}`;
resString = this.wrapWithSmartUnion(...alternatives);
} else {
resString = `z.union([${alternatives.join(',\r\n')}])${opt}`;
resString = `z.union([${alternatives.join(',\r\n')}])`;
}
}

if (!field.isRequired) {
resString += '.optional()';
}

if (field.isNullable) {
resString += '.nullable()';
}
Expand Down
24 changes: 24 additions & 0 deletions tests/integration/tests/plugins/zod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1097,4 +1097,28 @@ describe('Zod plugin tests', () => {
expect(schemas.UserSchema.safeParse({ id: 1, email: '[email protected]' }).success).toBeTruthy();
expect(schemas.UserPrismaCreateSchema.safeParse({ email: '[email protected]' }).success).toBeTruthy();
});

it('@json fields with @default should be optional', async () => {
const { zodSchemas } = await loadSchema(
`
type Foo {
a String
}

model Bar {
id Int @id @default(autoincrement())
foo Foo @json @default("{ \\"a\\": \\"a\\" }")
fooList Foo[] @json @default("[]")
}
`,
{
fullZod: true,
provider: 'postgresql',
pushDb: false,
}
);

// Ensure Zod Schemas correctly mark @default fields as optional
expect(zodSchemas.objects.BarCreateInputObjectSchema.safeParse({}).success).toBeTruthy();
});
});
Loading