Xiduzo
Xiduzo

Reputation: 1311

Prisma findFirstOrThrow does not throw

Using prisma I am trying to write some tests, however the findFirstOrThrow method (https://www.prisma.io/docs/reference/api-reference/prisma-client-reference#findfirstorthrow) does not seem to throw when nothing should be found. Instead it is returning the first database record it finds.

The following piece of code is what I am testing

console.log('sessionId', this.ctx.session?.user?.id);

const author = await this.db.author.findFirstOrThrow({
  where: { userId: this.ctx.session?.user?.id },
  select: { id: true },
});

console.log({ author });

And in my test output I get the following logs

RERUN  src/api/service.ts x31

stdout | src/api/service.test.ts > BlockService > block creation > without an author
sessionId undefined

stdout | src/api/service.test.ts > BlockService > block creation > without an author
{ author: { id: 'cle79pisg007hb2b8rhpii1ws' } }

So even though the this.ctx.session?.user?.id is undefined, prisma still returns the first author in the table.

What I've tried so far:

edit: I use prisma ^4.8.0

Upvotes: 1

Views: 1255

Answers (1)

Nurul Sundarani
Nurul Sundarani

Reputation: 7618

This is the expected behaviour.

If you will pass undefined then it is equivalent to not passing any userId. So, the query is equivalent to the following:

const author = await this.db.author.findFirstOrThrow({
  where: { },
  select: { id: true },
});

And this query would return the first record from database. For reference, here is the section that defines this behaviour.

Upvotes: 1

Related Questions