zenstackhq / zenstack

Fullstack TypeScript toolkit that enhances Prisma ORM with flexible Authorization layer for RBAC/ABAC/PBAC/ReBAC, offering auto-generated type-safe APIs and frontend hooks.
https://zenstack.dev
MIT License
2.07k stars 88 forks source link

validations on reference properties don't work #1563

Closed chunkerchunker closed 2 months ago

chunkerchunker commented 3 months ago

Description and expected behavior

Validations on reference properties work on creation, but fail on updates.

Following is a (contrived) example showing the issue:

    it('reference validation', async () => {
        const { enhance } = await loadSchema(
            `
        model ModelA {
            id String @id @default(cuid())
            ref ModelB[]
        }
        model ModelB {
            id String @id @default(cuid())
            ref ModelA? @relation(fields: [refId], references: [id])
            refId String?

            @@validate(refId != null, "refId must be set")
        }
        `,
            { enhancements: ['validation'] }
        );

        const db = enhance();

        const a = await db.modelA.create({data: {}});
        const b = await db.modelB.create({data: {refId: a.id}});

        await expect(db.modelB.update({ where: {id: b.id}, data: { refId: a.id } })).toResolveTruthy();
  }

The issue seems to be with the generated zod schema for ModelBPrismaUpdateSchema:

export const ModelBPrismaUpdateSchema = refineModelB(z.object({
    id: z.string()
}).partial());

I don't know what the correct fix is, but the following change fixes the test:

export const ModelBPrismaUpdateSchema = refineModelB(z.object({
    id: z.string()
}).merge(fkSchema).partial());

Environment:

Additional context Add any other context about the problem here.

ymc9 commented 2 months ago

Thanks for reporting this @chunkerchunker . The current zod schema generated for validating update input is excessively strict. I'm making a fix and will make it part of the next release.