Imagine you want to transfer money to your mother. You will need to withdraw money from your account and send it to hers.
You withdraw the money from your account, but when you go to make the transfer, the operation fails. You check your account and the money is no longer there, but it also hasn't reached your mother's account.
How can you prevent this from happening? Database transactions
What is?
A database transaction is a sequence of operations performed within a database management system as a single logical unit of work.
Transactions are closely related to database integrity and ensure the consistent state of a database even in the event of failure.
How it works?
The flow is simple and usually adopts an all or nothing policy:
- Begin the transaction
- Execute the operations (data manipulations, queries, etc)
- If no errors, commit the transaction, if an error occurs, rollback.
Typescript Example:
async create(transaction: Transaction, payable: Payable): Promise<Transaction> {
return this.prisma.$transaction(async (prisma) => {
const createdTransaction = await prisma.transaction.create({
data: {
...transaction,
},
});
await prisma.payable.create({
data: {
...payable,
},
});
return createdTransaction;
});
}
Top comments (3)
Thank you for your post, I learned new concept.
I'd like to collaborate with you in development
Hello ! Don't hesitate to put colors on your
codeblock
like this example for have to have a better understanding of your code 😎Thank you for your comment! It really makes a difference. I've fixed it.