File tree Expand file tree Collapse file tree 2 files changed +31
-5
lines changed
packages/schema/src/plugins/zod
tests/integration/tests/plugins Expand file tree Collapse file tree 2 files changed +31
-5
lines changed Original file line number Diff line number Diff line change @@ -282,22 +282,24 @@ export default class Transformer {
282
282
283
283
const fieldName = alternatives . some ( ( alt ) => alt . includes ( ':' ) ) ? '' : ` ${ field . name } :` ;
284
284
285
- const opt = ! field . isRequired ? '.optional()' : '' ;
286
-
287
285
let resString : string ;
288
286
289
287
if ( alternatives . length === 1 ) {
290
- resString = alternatives . join ( ',\r\n' ) ;
288
+ resString = alternatives [ 0 ] ;
291
289
} else {
292
290
if ( alternatives . some ( ( alt ) => alt . includes ( 'Unchecked' ) ) ) {
293
291
// if the union is for combining checked and unchecked input types, use `smartUnion`
294
292
// to parse with the best candidate at runtime
295
- resString = this . wrapWithSmartUnion ( ...alternatives ) + ` ${ opt } ` ;
293
+ resString = this . wrapWithSmartUnion ( ...alternatives ) ;
296
294
} else {
297
- resString = `z.union([${ alternatives . join ( ',\r\n' ) } ])${ opt } ` ;
295
+ resString = `z.union([${ alternatives . join ( ',\r\n' ) } ])` ;
298
296
}
299
297
}
300
298
299
+ if ( ! field . isRequired ) {
300
+ resString += '.optional()' ;
301
+ }
302
+
301
303
if ( field . isNullable ) {
302
304
resString += '.nullable()' ;
303
305
}
Original file line number Diff line number Diff line change @@ -1097,4 +1097,28 @@ describe('Zod plugin tests', () => {
1097
1097
expect ( schemas . UserSchema . safeParse ( { id : 1 , email : 'a@b.com' } ) . success ) . toBeTruthy ( ) ;
1098
1098
expect ( schemas . UserPrismaCreateSchema . safeParse ( { email : 'a@b.com' } ) . success ) . toBeTruthy ( ) ;
1099
1099
} ) ;
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
+ } ) ;
1100
1124
} ) ;
You can’t perform that action at this time.
0 commit comments