does trpc support prisma transactions?

I'm trying to run a $transaction() on TRPC router according to T3 app configs, but I need some help figuring out where to start. Also, can an object be mapped to the Prisma update function? I'm updating the number of products sold in a receipt, but I need help thinking of a good way to do it. Thank you so much for your attention and participation.
12 Replies
Neto
Neto3y ago
trpc is only a safe way of calling a backend function transations are only from the prisma side of it
sheng2808
sheng2808OP3y ago
I understand. I want to do a $Transaction on a TRPC mutation. How do you think I should go about it?
Amos
Amos3y ago
Just do a transaction? Lol
sheng2808
sheng2808OP3y ago
.mutation(async ({ ctx, input }) => { return await ctx.prisma.$transaction(async (tx) => { await tx.input.InvoiceItems.map(async element => { if (element.catergory === 'Product') { const currentInventory = await ctx.prisma.item.update({ where: { id: element.itemId }, data: { currentInventory: { decrement: element.quantity, } } }) if (currentInventory.currentInventory! < 0) { throw new Error(${element.itemId} is out of stock) } } }) }) })
sheng2808
sheng2808OP3y ago
this is what i did, sorry for the newbie questions 😢
Neto
Neto3y ago
its fine check the link may help you should check the inventory before starting the transaction btw to avoid locking the db
sheng2808
sheng2808OP3y ago
I'm still having trouble updating a dynamically sized dataset, I'm wondering if my code is still wrong or map doesn't work in this scenario...
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
sheng2808
sheng2808OP3y ago
Ahhh so that's the missing piece postInvoiceItems: protectedProcedure .input(z.object({ customerId: z.string(), discount: z.number(), discountType: z.string(), subtotal: z.number(), paymentType: z.string(), InvoiceItems: z.array(z.object({ itemId: z.number(), catergory: z.string(), //item: z.string(), unitPrice: z.number(), quantity: z.number(), discount: z.number(), discountType: z.string(), closeBy: z.string(), })), })) .mutation(async ({ ctx, input }) => { return ctx.prisma.$transaction(async () => { await Promise.all( input.InvoiceItems.map(async element => { if (element.catergory === 'Product') { const InvCheck = await ctx.prisma.item.findUnique({ where: { id: element.itemId, }, select: { currentInventory: true } }) if (InvCheck?.currentInventory! <= 0) { throw new Error(${element.itemId} is out of stock) } await ctx.prisma.item.update({ where: { id: element.itemId }, data: { currentInventory: { decrement: element.quantity, } } }) } }) ) }) }) That's my working implementation for it thank you all for the help and guidance ❤️
sheng2808
sheng2808OP3y ago
Also i had to npx prisma generate to get the interactiveTransactions working
Want results from more Discord servers?
Add your server