Rollback of Prisma Interactive Transaction in NestJS not working when throwing an error
Asked Answered
R

1

6

I am using the prisma ORM and NestJS and I got the following example code:

async createMerchant(data: Prisma.MerchantCreateInput): Promise<Merchant> {
  return await this.prisma.$transaction(async (): Promise<Merchant> => {
    await this.prisma.merchant.create({
      data,
    });
    throw new Error(`Some error`);
  });
}

I would expect that the transaction is rolled back as I have thrown an error, but it is not, it creates a new database entry.

Here is the example of the official documentation.

Is this maybe related to the dependency injection of NestJS and that the injected prisma service is not correctly recognizing the error? Or am I doing something wrong?

Regression answered 28/1, 2022 at 11:53 Comment(0)
C
15

As example shows you need to use prisma instance that is passed as an argument to your callback function, like that:

async createMerchant(data: Prisma.MerchantCreateInput): Promise<Merchant> {
  return await this.prisma.$transaction(async (prisma): Promise<Merchant> => {
    // Not this.prisma, but prisma from argument
    await prisma.merchant.create({
      data,
    });
    throw new Error(`Some error`);
  });
}
Chapman answered 28/1, 2022 at 12:34 Comment(2)
Can`t believe that I have not seen this! Thank you!Regression
@Danila, can i call rollback method explicitly?Organizer

© 2022 - 2024 — McMap. All rights reserved.