From 1e3d112e0f4729acc118bf5214479a7ed609548a Mon Sep 17 00:00:00 2001 From: falendikategar Date: Tue, 29 Oct 2024 15:44:10 +0700 Subject: [PATCH] update: changes to the backed endpoint post and patch due to the addition of validation so that questions cannot be duplicated in question management --- apps/backend/src/routes/questions/route.ts | 52 ++++++++++++++++++---- 1 file changed, 44 insertions(+), 8 deletions(-) diff --git a/apps/backend/src/routes/questions/route.ts b/apps/backend/src/routes/questions/route.ts index acdece9..8c551cc 100644 --- a/apps/backend/src/routes/questions/route.ts +++ b/apps/backend/src/routes/questions/route.ts @@ -1,6 +1,5 @@ -import { and, eq, ilike, isNull, or, sql } from "drizzle-orm"; +import { and, eq, ne, ilike, isNull, or, sql } from "drizzle-orm"; import { Hono } from "hono"; - import { z } from "zod"; import { HTTPException } from "hono/http-exception"; import db from "../../drizzle"; @@ -280,6 +279,24 @@ const questionsRoute = new Hono() return c.json({ message: "Sub aspect not found" }, 404); } + // Cek apakah question dengan subAspectId yang sama sudah ada + const duplicateQuestion = await db + .select() + .from(questions) + .where( + and( + eq(questions.subAspectId, questionData.subAspectId), + eq(questions.question, questionData.question) + ) + ); + + if (duplicateQuestion.length > 0) { + return c.json( + { message: "Pertanyaan dengan sub-aspek yang sama sudah ada" }, + 409 + ); + } + // Insert question data into the questions table const question = await db .insert(questions) @@ -294,17 +311,16 @@ const questionsRoute = new Hono() // Insert options data if provided if (questionData.options && questionData.options.length > 0) { - const optionsData = questionData.options.map((option) => ({ - questionId: questionId, - text: option.text, - score: option.score, + const optionsData = questionData.options.map((option) => ({ + questionId: questionId, + text: option.text, + score: option.score, })); await db.insert(options).values(optionsData); } - return c.json( - { + return c.json({ message: "Question and options created successfully", data: question[0], }, @@ -333,6 +349,26 @@ const questionsRoute = new Hono() .where(and(eq(questions.id, questionId), isNull(questions.deletedAt))); if (!question[0]) throw notFound(); + + // Check if the combination of subAspectId and question already exists (except for this question) + const duplicateQuestion = await db + .select() + .from(questions) + .where( + and( + eq(questions.subAspectId, questionData.subAspectId), + eq(questions.question, questionData.question), + ne(questions.id, questionId), // Ignore questions that are being updated + isNull(questions.deletedAt) + ) + ); + + if (duplicateQuestion.length > 0) { + return c.json( + { message: "Pertanyaan dengan sub-aspek yang sama sudah ada" }, + 409 + ); + } // Update question data await db