From 60d1ec3454a811ccd34363f1c65dcc9c8e74dd5e Mon Sep 17 00:00:00 2001 From: ymc9 <104139426+ymc9@users.noreply.github.com> Date: Fri, 15 Nov 2024 16:14:07 -0800 Subject: [PATCH] fix: allow 'null' values for optional fields in custom types --- .../enhance/model-typedef-generator.ts | 5 ++- tests/regression/tests/issue-1857.test.ts | 45 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 tests/regression/tests/issue-1857.test.ts diff --git a/packages/schema/src/plugins/enhancer/enhance/model-typedef-generator.ts b/packages/schema/src/plugins/enhancer/enhance/model-typedef-generator.ts index 21ede7a64..00f16095f 100644 --- a/packages/schema/src/plugins/enhancer/enhance/model-typedef-generator.ts +++ b/packages/schema/src/plugins/enhancer/enhance/model-typedef-generator.ts @@ -17,8 +17,11 @@ export function generateTypeDefType(sourceFile: SourceFile, decl: TypeDef) { field.comments.forEach((c) => writer.writeLine(` * ${unwrapTripleSlashComment(c)}`)); writer.writeLine(` */`); } + // optional fields are also nullable (to be consistent with Prisma) writer.writeLine( - ` ${field.name}${field.type.optional ? '?' : ''}: ${zmodelTypeToTsType(field.type)};` + ` ${field.name}${field.type.optional ? '?' : ''}: ${zmodelTypeToTsType(field.type)}${ + field.type.optional ? ' | null' : '' + };` ); }); }); diff --git a/tests/regression/tests/issue-1857.test.ts b/tests/regression/tests/issue-1857.test.ts new file mode 100644 index 000000000..fcd730017 --- /dev/null +++ b/tests/regression/tests/issue-1857.test.ts @@ -0,0 +1,45 @@ +import { loadSchema } from '@zenstackhq/testtools'; + +describe('issue 1857', () => { + it('regression', async () => { + const { zodSchemas } = await loadSchema( + ` + type JSONContent { + type String + text String? + } + + model Post { + id String @id @default(uuid()) + content JSONContent @json + @@allow('all', true) + } + `, + { + provider: 'postgresql', + pushDb: false, + compile: true, + extraSourceFiles: [ + { + name: 'main.ts', + content: ` + import { PrismaClient } from '@prisma/client'; + import { enhance } from '.zenstack/enhance'; + + async function main() { + const prisma = new PrismaClient(); + await prisma.post.create({ + data: { + content: { type: 'foo', text: null } + } + }); + } + `, + }, + ], + } + ); + + zodSchemas.models.JSONContentSchema.parse({ type: 'foo', text: null }); + }); +});