Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
refactor: transaction
Marc Seitz6cec8b95abf0
diff --git a/pages/api/teams/[teamId]/documents/[id]/update-name.ts b/pages/api/teams/[teamId]/documents/[id]/update-name.tsindex 2576138f..0ffedb58 100644--- a/pages/api/teams/[teamId]/documents/[id]/update-name.ts+++ b/pages/api/teams/[teamId]/documents/[id]/update-name.ts@@ -2,11 +2,19 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { z } from "zod";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";+const updateNameSchema = z.object({+ name: z+ .string()+ .min(1, "Document name is required")+ .max(255, "Document name too long"),+});+export default async function handle(req: NextApiRequest,res: NextApiResponse,@@ -23,6 +31,17 @@ export default async function handle(const userId = (session.user as CustomUser).id;try {+ // Validate input using Zod+ const validationResult = updateNameSchema.safeParse(req.body);+ if (!validationResult.success) {+ return res.status(400).json({+ error: "Invalid input",+ details: validationResult.error.issues,+ });+ }++ const { name } = validationResult.data;+const teamAccess = await prisma.userTeam.findUnique({where: {userId_teamId: {@@ -36,27 +55,34 @@ export default async function handle(return res.status(401).end("Unauthorized");}- const document = await prisma.document.findUnique({- where: {- id: docId,- teamId,- },- select: { id: true },+ // Atomic transaction to update document name+ const result = await prisma.$transaction(async (tx) => {+ // Perform atomic update with both teamId and id in the filter+ const document = await tx.document.findUnique({+ where: {+ id: docId,+ teamId: teamId, // Ensure document belongs to the team+ },+ select: { id: true },+ });++ if (!document) {+ return res.status(404).json({ error: "Document not found" });+ }++ const updateResult = await tx.document.update({+ where: { id: docId, teamId },+ data: { name: name },+ });++ return updateResult;});- if (!document) {+ // Check if any rows were affected+ if (!result) {return res.status(404).json({ error: "Document not found" });}- await prisma.document.update({- where: {- id: docId,- },- data: {- name: req.body.name,- },- });-return res.status(200).json({ message: "Document name updated!" });} catch (error) {errorhandler(error, res);