Skip to content

Commit f642aff

Browse files
committed
fix(zod): Required fields with a default value should be optional
1 parent 7632f24 commit f642aff

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

packages/schema/src/plugins/zod/transformer.ts

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -282,22 +282,24 @@ export default class Transformer {
282282

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

285-
const opt = !field.isRequired ? '.optional()' : '';
286-
287285
let resString: string;
288286

289287
if (alternatives.length === 1) {
290-
resString = alternatives.join(',\r\n');
288+
resString = alternatives[0];
291289
} else {
292290
if (alternatives.some((alt) => alt.includes('Unchecked'))) {
293291
// if the union is for combining checked and unchecked input types, use `smartUnion`
294292
// to parse with the best candidate at runtime
295-
resString = this.wrapWithSmartUnion(...alternatives) + `${opt}`;
293+
resString = this.wrapWithSmartUnion(...alternatives);
296294
} else {
297-
resString = `z.union([${alternatives.join(',\r\n')}])${opt}`;
295+
resString = `z.union([${alternatives.join(',\r\n')}])`;
298296
}
299297
}
300298

299+
if (!field.isRequired) {
300+
resString += '.optional()';
301+
}
302+
301303
if (field.isNullable) {
302304
resString += '.nullable()';
303305
}

tests/integration/tests/plugins/zod.test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1097,4 +1097,28 @@ describe('Zod plugin tests', () => {
10971097
expect(schemas.UserSchema.safeParse({ id: 1, email: 'a@b.com' }).success).toBeTruthy();
10981098
expect(schemas.UserPrismaCreateSchema.safeParse({ email: 'a@b.com' }).success).toBeTruthy();
10991099
});
1100+
1101+
it('@json fields with @default should be optional', async () => {
1102+
const { zodSchemas } = await loadSchema(
1103+
`
1104+
type Foo {
1105+
a String
1106+
}
1107+
1108+
model Bar {
1109+
id Int @id @default(autoincrement())
1110+
foo Foo @json @default("{ \\"a\\": \\"a\\" }")
1111+
fooList Foo[] @json @default("[]")
1112+
}
1113+
`,
1114+
{
1115+
fullZod: true,
1116+
provider: 'postgresql',
1117+
pushDb: false,
1118+
}
1119+
);
1120+
1121+
// Ensure Zod Schemas correctly mark @default fields as optional
1122+
expect(zodSchemas.objects.BarCreateInputObjectSchema.safeParse({}).success).toBeTruthy();
1123+
});
11001124
});

0 commit comments

Comments
 (0)