From 7fb5e1a62b44b6090d3d165b11c494f3582c4c6d Mon Sep 17 00:00:00 2001 From: Joao Correia Date: Wed, 5 Feb 2025 18:55:31 +0000 Subject: [PATCH] fix typo and bug on exam edit. It was throwing an exception if it found an id with the same owners, but should throw when the owners are different. It was also throwing an error if owners was not set in exam. --- src/pages/api/exam/[module]/index.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/src/pages/api/exam/[module]/index.ts b/src/pages/api/exam/[module]/index.ts index 563b953b..af9a7783 100644 --- a/src/pages/api/exam/[module]/index.ts +++ b/src/pages/api/exam/[module]/index.ts @@ -40,13 +40,13 @@ async function GET(req: NextApiRequest, res: NextApiResponse) { } async function POST(req: NextApiRequest, res: NextApiResponse) { - const user = await requestUser(req, res) + const user = await requestUser(req, res); if (!user) return res.status(401).json({ ok: false }); const { module } = req.query as { module: string }; const session = client.startSession(); - const entities = isAdmin(user) ? [] : mapBy(user.entities, 'id') + const entities = isAdmin(user) ? [] : mapBy(user.entities, "id"); try { const exam = { @@ -64,8 +64,16 @@ async function POST(req: NextApiRequest, res: NextApiResponse) { // owners, throw exception if there is, else allow editing const ownersSet = new Set(docSnap?.owners || []); - if (docSnap !== null && docSnap?.owners?.length === exam.owners.lenght && exam.owners.every((e: string) => ownersSet.has(e))) { - throw new Error("Name already exists"); + if (docSnap !== null) { + if (docSnap.owners === undefined) { + docSnap.owners = []; + } + if (exam.owners === undefined) { + exam.owners = []; + } + if (docSnap.owners?.length !== exam.owners?.length || !exam.owners?.every((e: string) => ownersSet.has(e))) { + throw new Error("Name already exists"); + } } await db.collection(module).updateOne( @@ -73,13 +81,12 @@ async function POST(req: NextApiRequest, res: NextApiResponse) { { $set: { id: req.body.id, ...exam } }, { upsert: true, - session + session, } ); }); res.status(200).json(exam); - } catch (error) { console.error("Transaction failed: ", error); res.status(500).json({ ok: false, error: (error as any).message });