Skip to content
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: 'a@b.com' }).success).toBeTruthy();
expect(schemas.UserPrismaCreateSchema.safeParse({ email: 'a@b.com' }).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