update: changes to the backed endpoint post and patch due to the addition of validation so that questions cannot be duplicated in question management

This commit is contained in:
falendikategar 2024-10-29 15:44:10 +07:00
parent 7dd5b41b40
commit 1e3d112e0f

View File

@ -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<HonoEnv>()
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)
@ -303,8 +320,7 @@ const questionsRoute = new Hono<HonoEnv>()
await db.insert(options).values(optionsData);
}
return c.json(
{
return c.json({
message: "Question and options created successfully",
data: question[0],
},
@ -334,6 +350,26 @@ const questionsRoute = new Hono<HonoEnv>()
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
.update(questions)