TryHard
TryHard

Reputation: 299

How to use DB [ transaction , comit, rollback ] in adonis js

I want to use try catch with DB transaction for if I get something error I want the database rollback all of my query in try function

Here is my try. I comment const empImg because I want to test. It's not rollback await emp.save(); after the query error unknown empImg

  const trx = await Database.beginTransaction()
  try {
      const user = await auth.getUser();
      const emp = new Employee();
      emp.fill(empData);
      emp.merge({ update_by: user.name  })
      await emp.save();
      // const empImg = new EmployeePhoto();
      empImg.name = user.name;
      await empImg.save();
      await trx.commit()
    } catch (error) {
      await trx.rollback()
      throw new InvalidAccessException();
    }

Of course I can just put

emp.delete(); in catch but I've to check which query error and delete it.

How can I do something like this If something error I want to rollback my emp and empImg?

Upvotes: 0

Views: 2263

Answers (1)

alvisx
alvisx

Reputation: 61

You can send trx object to Lucid functions for working with transactions mechanism, e.g. await emp.save(trx);

  const trx = await Database.beginTransaction()

  try {
      const user = await auth.getUser();
      const emp = new Employee();
      emp.fill(empData);
      emp.merge({ update_by: user.name  })
      await emp.save(trx);
      // const empImg = new EmployeePhoto();
      empImg.name = user.name;
      await empImg.save(trx);
      await trx.commit()
    } catch (error) {
      await trx.rollback()
      throw new InvalidAccessException();
    }

Transactions in AdonisJS Docs

Upvotes: 2

Related Questions