Implementing Transactions with Prisma for Atomic Database Operations
00:00 This is a little bit easier and also a little bit trickier than you might expect. So the easy part of it is we simply add prisma.transaction and Copilot wants us to do the array syntax. I don't wanna do that. We're gonna have an async function and it's gonna take an argument I'm gonna call $prisma.
00:19 This is how I can differentiate between the regular Prisma and the transactional Prisma. A lot of people will also use TX to represent a transaction, but I don't know, $prisma just makes sense to me. So then we're gonna take all this stuff and we're gonna move it into the transaction function.
00:39 And then we're gonna update every reference to Prisma in here to that $prisma. So we are done and this will absolutely work. So actually, yeah, let's go ahead and just try it out. So refresh, we close this out and here actually, let's add an error.
00:59 So we're gonna throw an error at the end. So everything, you would expect everything to work just fine and all of those transaction or those queries are completing, but then we have some sort of error at the end of our stuff. So we get that error and none of those things actually did happen. And that will happen regardless of where we end up
01:19 putting this error, we stick it right here. Same story goes right here. We change this stuff. And even though this will all technically work, so we get past here, we're not actually going to submit it because we get that error. So that's exactly what we want.
01:35 Now, this little bit, why is this throwing a big fit? Well, the reason is because this note ID could technically be undefined. And the reason is because this is defined inside a callback function. So before it didn't have a problem with this, before it was like, yeah, okay, whatever.
01:53 That's no big deal because, and it said it's a string. And that's because we had our invariant up here making sure that the params note ID is a string. But once you stick it into a callback, TypeScript is like, I don't know, I'm confused. And so what we're gonna do just to fix this
02:13 is we'll say note ID equals params and then we'll verify that. And with that, then we can just use note ID as it is and we can move this up here. And now it's all happy and no problems. So fundamentally, all that we really did
02:31 was we took this group of transactions or of Prisma queries and stuck it inside of a transaction callback and then swapped it with the transactional client so that all of these things succeed or fail together. And that is how you do transactions with Prisma.