Search code examples
transactionsprisma

Error not catching in Prisma Transactions


I am trying to use transaction in Prisma, I have two database insertions, In the first query it performs correctly but in the second I get an error in console that I am missing some parameters in the tx.price_of_Product.create(). Even though I have an error it returns success true that is in the end of the try statement. I have also used previewFeatures = ["interactiveTransactions"] in the schema.prisma.

const prisma = new PrismaClient();
const STORE_PRODUCT = async (req, res) => {
  try {
    await prisma.$transaction(async (tx) => {
     const { name, description, price, colors } = req.body;

       const product = await tx.products.create({
        data: {
          name,
          description,
          business_id: 2,
          created_by: 1,
        },
      });

      colors.forEach(async (color) => {
        await tx.product_Color.create({   //here i get an error
          data: {
            name: color,
            product_id: product.id,
          },
        });
      });

      return res.status(200).json({
        success: true,
      });

  catch (error) {
    console.log(error);

    return res.status(500).json({
      success: false,
      message: error.message,
    });
  }
};

Solution

  • Thanks to Nurul Sundarani,

    The problem was with for loop, after fixing that the transaction works perfectly.

      for (const color of colors) {
            await tx.Product_Color.create({
              data: {
                name: color.name,
                quantity: color.quantity,
                product_id: product.id,
              },
            });
          }