Shashi Prakash Gautam
Shashi Prakash Gautam

Reputation: 434

How to implement transaction in Loopback 4

I am making two repository calls to update the data in two different tables in db. I want to implement a transaction. Need help on how to perform this. https://loopback.io/doc/en/lb4/Using-database-transactions.html From the documentation it looks like transaction can be performed in only one repository not between two repositories.

const created = await repo.create({title: 'Groceries'}, {transaction: tx});
const updated = await repo.update(
  {title: 'Errands', id: created.id},
  {transaction: tx},
);

// commit the transaction to persist the changes
await tx.commit();

But I want

const created = await repo1.create({title: 'Groceries'}, {transaction: tx});
const updated = await repo2.update(
  {title: 'Errands', id: created.id},
  {transaction: tx},
);

// commit the transaction to persist the changes
await tx.commit();

Anyone has any idea how to do this.

Upvotes: 0

Views: 595

Answers (1)

Madaky
Madaky

Reputation: 387

const created = await repo1.create({title: 'Groceries'}, {transaction: tx});
const updated = await repo2.update( {title: 'Errands', id: created.id},{transaction: tx}, );

// commit the transaction to persist the changes await tx.commit();

Yes it is possible, if your repo1 and repo2 belongs to same datasource.

more information here

Upvotes: 1

Related Questions