W
Wasp•3w ago
fustuk.

Prisma transactions

How can I use transactions in wasp?
5 Replies
kapa.ai
kapa.ai•3w ago
Hi @fustuk.. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To use Prisma transactions in Wasp, you can access the Prisma client directly and utilize its transaction capabilities. Here's how you can do it: 1. Import the Prisma client in your server-side code:
import prisma from '@wasp/dbClient'
import prisma from '@wasp/dbClient'
2. Use the $transaction method provided by Prisma to perform multiple operations within a transaction. Here's an example:
const [posts, totalPosts] = await prisma.$transaction([
context.entities.Post.findMany({
where: { title: { contains: 'prisma' } }
}),
context.entities.Post.count(),
])
const [posts, totalPosts] = await prisma.$transaction([
context.entities.Post.findMany({
where: { title: { contains: 'prisma' } }
}),
context.entities.Post.count(),
])
This example demonstrates how to perform multiple database operations (finding posts and counting them) within a single transaction. It's important to note that you should typically use transactions within Wasp actions or queries, where you have access to the context.entities object. If you're working outside of these contexts, you can use prisma directly instead of context.entities. For more detailed information on using entities and Prisma in Wasp, you can refer to the Wasp documentation on Entities. Remember that while Wasp provides a convenient abstraction layer over Prisma, you can always access Prisma's full functionality when needed for more complex operations like transactions. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @fustuk., I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
miho
miho•3w ago
I think what the bot suggested should work đź‘Ť I'd just use the import { prisma } from 'wasp/server' way of importing PrismaClient
fustuk.
fustuk.OP•3w ago
thanks if I import the prisma instance, do I need to use context.entities, can I directly use any model I need, ex:
await prisma.$transaction(async (tx: any) => {
const subscription = await tx.subscription.update({
await prisma.$transaction(async (tx: any) => {
const subscription = await tx.subscription.update({
miho
miho•3w ago
context.entities.User === prisma.user so yep, nothing Wasp specific. I believe you should use the tx to make sure the queries are executed in the transaction
fustuk.
fustuk.OP•3w ago
thanks

Did you find this page helpful?