Skip to content

Commit

Permalink
fix(zod): don't include fields marked @ignore in schemas
Browse files Browse the repository at this point in the history
  • Loading branch information
ymc9 committed Nov 22, 2024
1 parent 0625234 commit fcc2909
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
10 changes: 6 additions & 4 deletions packages/schema/src/plugins/zod/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -396,16 +396,18 @@ 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) ||
// regular fields only
(!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);

Expand Down Expand Up @@ -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(', ')} })`
Expand Down
16 changes: 16 additions & 0 deletions tests/integration/tests/plugins/zod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: '[email protected]' }).success).toBeTruthy();
expect(schemas.UserPrismaCreateSchema.safeParse({ email: '[email protected]' }).success).toBeTruthy();
});
});

0 comments on commit fcc2909

Please sign in to comment.