Skip to content

Commit 3eab438

Browse files
committed
fix(zod): support @default for BigInt values
Zod schemas fail to generate when using a `BigInt` type and a `@default` field, since generated Zod files use a `number` literal instead of a `BigInt` literal for the default value.
1 parent 714220e commit 3eab438

File tree

2 files changed

+10
-1
lines changed

2 files changed

+10
-1
lines changed

packages/schema/src/plugins/zod/utils/schema-gen.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,13 @@ export function makeFieldSchema(field: DataModelField) {
152152
} else {
153153
const schemaDefault = getFieldSchemaDefault(field);
154154
if (schemaDefault !== undefined) {
155-
schema += `.default(${schemaDefault})`;
155+
if (field.type.type === 'BigInt') {
156+
// we can't use the `n` BigInt literal notation, since it needs
157+
// ES2020 or later, which TypeScript doesn't use by default
158+
schema += `.default(BigInt("${schemaDefault}"))`;
159+
} else {
160+
schema += `.default(${schemaDefault})`;
161+
}
156162
}
157163

158164
if (field.type.optional) {

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ describe('Zod plugin tests', () => {
6161
authorId Int?
6262
published Boolean @default(false)
6363
viewCount Int @default(0)
64+
viewMilliseconds BigInt @default(0)
6465
}
6566
`,
6667
{ addPrelude: false, pushDb: false }
@@ -188,11 +189,13 @@ describe('Zod plugin tests', () => {
188189
expect(schemas.PostPrismaCreateSchema.safeParse({ title: 'a' }).success).toBeFalsy();
189190
expect(schemas.PostPrismaCreateSchema.safeParse({ title: 'abcde' }).success).toBeTruthy();
190191
expect(schemas.PostPrismaCreateSchema.safeParse({ viewCount: 1 }).success).toBeTruthy();
192+
expect(schemas.PostPrismaCreateSchema.safeParse({ viewMilliseconds: 1n }).success).toBeTruthy();
191193

192194
expect(schemas.PostPrismaUpdateSchema.safeParse({ title: 'a' }).success).toBeFalsy();
193195
expect(schemas.PostPrismaUpdateSchema.safeParse({ title: 'abcde' }).success).toBeTruthy();
194196
expect(schemas.PostPrismaUpdateSchema.safeParse({ viewCount: 1 }).success).toBeTruthy();
195197
expect(schemas.PostPrismaUpdateSchema.safeParse({ viewCount: { increment: 1 } }).success).toBeTruthy();
198+
expect(schemas.PostPrismaUpdateSchema.safeParse({ viewMilliseconds: 1n }).success).toBeTruthy();
196199
});
197200

198201
it('mixed casing', async () => {

0 commit comments

Comments
 (0)