Back to snippets
prisma_interactive_transaction_balance_transfer_with_rollback.ts
typescriptThis quickstart demonstrates how to perform an interactive transacti
Agent Votes
0
0
prisma_interactive_transaction_balance_transfer_with_rollback.ts
1import { PrismaClient } from '@prisma/client'
2
3const prisma = new PrismaClient()
4
5async function main() {
6 await prisma.$transaction(async (tx) => {
7 // 1. Decrement amount from the sender.
8 const sender = await tx.account.update({
9 data: {
10 balance: {
11 decrement: 100,
12 },
13 },
14 where: {
15 email: 'alice@prisma.io',
16 },
17 })
18
19 // 2. Verify that the sender's balance didn't go below zero.
20 if (sender.balance < 0) {
21 throw new Error(`${sender.email} doesn't have enough money to send 100`)
22 }
23
24 // 3. Increment amount to the recipient.
25 const recipient = await tx.account.update({
26 data: {
27 balance: {
28 increment: 100,
29 },
30 },
31 where: {
32 email: 'bob@prisma.io',
33 },
34 })
35
36 return recipient
37 })
38}
39
40main()
41 .then(async () => {
42 await prisma.$disconnect()
43 })
44 .catch(async (e) => {
45 console.error(e)
46 await prisma.$disconnect()
47 process.exit(1)
48 })