From 7b4836870acfad42b6ced974d01cfcdd4a0d4fb9 Mon Sep 17 00:00:00 2001 From: ymc9 <104139426+ymc9@users.noreply.github.com> Date: Fri, 7 Jun 2024 23:22:55 +0800 Subject: [PATCH] fix(delegate): null reference when reading an optional relation --- packages/runtime/src/enhancements/delegate.ts | 8 +++ tests/regression/tests/issue-1483.test.ts | 68 +++++++++++++++++++ 2 files changed, 76 insertions(+) create mode 100644 tests/regression/tests/issue-1483.test.ts diff --git a/packages/runtime/src/enhancements/delegate.ts b/packages/runtime/src/enhancements/delegate.ts index 145de9f7c..edbaed78d 100644 --- a/packages/runtime/src/enhancements/delegate.ts +++ b/packages/runtime/src/enhancements/delegate.ts @@ -1101,6 +1101,10 @@ export class DelegateProxyHandler extends DefaultPrismaProxyHandler { } private assembleUp(model: string, entity: any) { + if (!entity) { + return entity; + } + const result: any = {}; const base = this.getBaseModel(model); @@ -1148,6 +1152,10 @@ export class DelegateProxyHandler extends DefaultPrismaProxyHandler { } private assembleDown(model: string, entity: any) { + if (!entity) { + return entity; + } + const result: any = {}; const modelInfo = getModelInfo(this.options.modelMeta, model, true); diff --git a/tests/regression/tests/issue-1483.test.ts b/tests/regression/tests/issue-1483.test.ts new file mode 100644 index 000000000..ee947ae2c --- /dev/null +++ b/tests/regression/tests/issue-1483.test.ts @@ -0,0 +1,68 @@ +import { loadSchema } from '@zenstackhq/testtools'; +describe('issue 1483', () => { + it('regression', async () => { + const { enhance } = await loadSchema( + ` + model User { + @@auth + id String @id + edits Edit[] + @@allow('all', true) + } + + model Entity { + + id String @id @default(cuid()) + name String + edits Edit[] + + type String + @@delegate(type) + + @@allow('all', true) + } + + model Person extends Entity { + } + + model Edit { + id String @id @default(cuid()) + + authorId String? + author User? @relation(fields: [authorId], references: [id], onDelete: Cascade, onUpdate: NoAction) + + entityId String + entity Entity @relation(fields: [entityId], references: [id], onDelete: Cascade, onUpdate: NoAction) + + @@allow('all', true) + } + ` + ); + + const db = enhance(); + await db.edit.deleteMany({}); + await db.person.deleteMany({}); + await db.user.deleteMany({}); + + const person = await db.person.create({ + data: { + name: 'test', + }, + }); + + await db.edit.create({ + data: { + entityId: person.id, + }, + }); + + await expect( + db.edit.findMany({ + include: { + author: true, + entity: true, + }, + }) + ).resolves.toHaveLength(1); + }); +});