0

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,
    });
  }
};
Illyrian
  • 429
  • 4
  • 16
  • 2
    Instead of forEach loop, can you try using a normal for loop? await would not work as expected in the forEach loop: https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Nurul Sundarani Oct 25 '22 at 16:09
  • @NurulSundarani You are correct, the for loop was the problem. – Illyrian Oct 28 '22 at 10:15

1 Answers1

1

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,
          },
        });
      }
Illyrian
  • 429
  • 4
  • 16