From fcc2909024aa4090a0715f5d54174621b8cacfba Mon Sep 17 00:00:00 2001 From: ymc9 <104139426+ymc9@users.noreply.github.com> Date: Thu, 21 Nov 2024 17:54:19 -0800 Subject: [PATCH] fix(zod): don't include fields marked `@ignore` in schemas --- packages/schema/src/plugins/zod/generator.ts | 10 ++++++---- tests/integration/tests/plugins/zod.test.ts | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/packages/schema/src/plugins/zod/generator.ts b/packages/schema/src/plugins/zod/generator.ts index 46e6505fe..b0c138857 100644 --- a/packages/schema/src/plugins/zod/generator.ts +++ b/packages/schema/src/plugins/zod/generator.ts @@ -396,7 +396,9 @@ export const ${typeDef.name}Schema = ${refineFuncName}(${noRefineSchema}); }); this.sourceFiles.push(sf); sf.replaceWithText((writer) => { - const scalarFields = model.fields.filter( + const allFields = model.fields.filter((f) => !hasAttribute(f, '@ignore')); + + const scalarFields = allFields.filter( (field) => // id fields are always included isIdField(field) || @@ -404,8 +406,8 @@ export const ${typeDef.name}Schema = ${refineFuncName}(${noRefineSchema}); (!isDataModel(field.type.reference?.ref) && !isForeignKeyField(field)) ); - const relations = model.fields.filter((field) => isDataModel(field.type.reference?.ref)); - const fkFields = model.fields.filter((field) => isForeignKeyField(field)); + const relations = allFields.filter((field) => isDataModel(field.type.reference?.ref)); + const fkFields = allFields.filter((field) => isForeignKeyField(field)); this.addPreludeAndImports(model, writer, output); @@ -461,7 +463,7 @@ export const ${typeDef.name}Schema = ${refineFuncName}(${noRefineSchema}); const refineFuncName = this.createRefineFunction(model, writer); // delegate discriminator fields are to be excluded from mutation schemas - const delegateDiscriminatorFields = model.fields.filter((field) => isDiscriminatorField(field)); + const delegateDiscriminatorFields = allFields.filter((field) => isDiscriminatorField(field)); const omitDiscriminators = delegateDiscriminatorFields.length > 0 ? `.omit({ ${delegateDiscriminatorFields.map((f) => `${f.name}: true`).join(', ')} })` diff --git a/tests/integration/tests/plugins/zod.test.ts b/tests/integration/tests/plugins/zod.test.ts index aba94261c..226da18f7 100644 --- a/tests/integration/tests/plugins/zod.test.ts +++ b/tests/integration/tests/plugins/zod.test.ts @@ -1081,4 +1081,20 @@ describe('Zod plugin tests', () => { success: false, }); }); + + it('ignores "@ignore" fields', async () => { + const { zodSchemas } = await loadSchema( + ` + model User { + id Int @id @default(autoincrement()) + email String @unique + password String @ignore + } + ` + ); + + const schemas = zodSchemas.models; + expect(schemas.UserSchema.safeParse({ id: 1, email: 'a@b.com' }).success).toBeTruthy(); + expect(schemas.UserPrismaCreateSchema.safeParse({ email: 'a@b.com' }).success).toBeTruthy(); + }); });