From e9e2fce949da9e5e9a8fcce39191f637eede8d48 Mon Sep 17 00:00:00 2001 From: dinesh Date: Wed, 27 May 2026 23:31:00 +0530 Subject: [PATCH] fix: wrap card creation in transaction to prevent race condition --- apps/backend/src/routes/cards.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/apps/backend/src/routes/cards.ts b/apps/backend/src/routes/cards.ts index 121665d4..d9e2402c 100644 --- a/apps/backend/src/routes/cards.ts +++ b/apps/backend/src/routes/cards.ts @@ -107,9 +107,12 @@ export async function cardRoutes(app: FastifyInstance): Promise { // Check if user's first card -> make it default. // Prisma wraps the nested cardLinks.create inside card.create in a single // implicit transaction, so either both the card and its links are written or neither is. - const cardCount = await app.prisma.card.count({ where: { userId } }); + const card = await app.prisma.$transaction(async (tx) => { + const cardCount = await tx.card.count({ + where: { userId }, + }); - const card = await app.prisma.card.create({ + return tx.card.create({ data: { userId, title: parsed.data.title, @@ -128,7 +131,7 @@ export async function cardRoutes(app: FastifyInstance): Promise { }, }, }); - + }}; const response = { id: card.id, title: card.title,