diff --git a/packages/runtime/src/enhancements/default-auth.ts b/packages/runtime/src/enhancements/default-auth.ts index ba1ead7f1..1408a93b7 100644 --- a/packages/runtime/src/enhancements/default-auth.ts +++ b/packages/runtime/src/enhancements/default-auth.ts @@ -1,12 +1,19 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-explicit-any */ -import { FieldInfo, NestedWriteVisitor, PrismaWriteActionType, enumerate, getFields, requireField } from '../cross'; -import { clone } from '../cross'; +import { + FieldInfo, + NestedWriteVisitor, + PrismaWriteActionType, + clone, + enumerate, + getFields, + requireField, +} from '../cross'; import { DbClientContract } from '../types'; import { EnhancementContext, InternalEnhancementOptions } from './create-enhancement'; import { DefaultPrismaProxyHandler, PrismaProxyActions, makeProxy } from './proxy'; -import { isUnsafeMutate } from './utils'; +import { isUnsafeMutate, prismaClientValidationError } from './utils'; /** * Gets an enhanced Prisma client that supports `@default(auth())` attribute. @@ -143,7 +150,11 @@ class DefaultAuthHandler extends DefaultPrismaProxyHandler { private getDefaultValueFromAuth(fieldInfo: FieldInfo) { if (!this.userContext) { - throw new Error(`Evaluating default value of field \`${fieldInfo.name}\` requires a user context`); + throw prismaClientValidationError( + this.prisma, + this.options.prismaModule, + `Evaluating default value of field \`${fieldInfo.name}\` requires a user context` + ); } return fieldInfo.defaultValueProvider?.(this.userContext); } diff --git a/tests/regression/tests/issue-1596.test.ts b/tests/regression/tests/issue-1596.test.ts new file mode 100644 index 000000000..62eedfd5f --- /dev/null +++ b/tests/regression/tests/issue-1596.test.ts @@ -0,0 +1,34 @@ +import { isPrismaClientValidationError } from '@zenstackhq/runtime'; +import { loadSchema } from '@zenstackhq/testtools'; + +describe('issue 1596', () => { + it('regression', async () => { + const { enhance } = await loadSchema( + ` + model User { + id Int @id + posts Post[] + } + + model Post { + id Int @id + title String + author User @relation(fields: [authorId], references: [id]) + authorId Int @default(auth().id) + } + ` + ); + + const db = enhance(); + + try { + await db.post.create({ data: { title: 'Post1' } }); + } catch (e) { + // eslint-disable-next-line jest/no-conditional-expect + expect(isPrismaClientValidationError(e)).toBe(true); + return; + } + + throw new Error('Expected error'); + }); +});