Skip to content

Commit

Permalink
Merge pull request #140 from CS3219-AY2425S1/fix/bug/update-question-…
Browse files Browse the repository at this point in the history
…endpoint

Fix duplicate handling in update questions backend
  • Loading branch information
jq1836 authored Sep 26, 2024
2 parents be87f97 + ffc2749 commit b8c0ae6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
18 changes: 13 additions & 5 deletions question-service/app/crud/questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,22 @@ async def delete_question(question_id: str):

async def update_question_by_id(question_id: str, question_data: UpdateQuestionModel):
existing_question = await question_collection.find_one({"_id": ObjectId(question_id)})

if existing_question is None:
return None

update_data = question_data.model_dump(exclude_unset=True)

# Check if the new title already exists and belongs to another question
if "title" in update_data and update_data["title"] != existing_question["title"]:
existing_title = await question_collection.find_one({"title": update_data["title"]})
if existing_title and str(existing_title["_id"]) != question_id:
return "duplicate_title"

updated_data = {"$set": question_data.model_dump(exclude_unset=True)}
if not updated_data["$set"]:
if not update_data:
return existing_question
await question_collection.update_one({"_id": ObjectId(question_id)}, updated_data)

await question_collection.update_one({"_id": ObjectId(question_id)}, {"$set": update_data})
return await question_collection.find_one({"_id": ObjectId(question_id)})

async def batch_create_questions(questions: List[CreateQuestionModel]):
Expand All @@ -62,4 +70,4 @@ async def batch_create_questions(questions: List[CreateQuestionModel]):

result = await question_collection.insert_many(new_questions)

return {"message": f"{len(result.inserted_ids)} questions added successfully."}
return {"message": f"{len(result.inserted_ids)} questions added successfully."}
4 changes: 4 additions & 0 deletions question-service/app/routers/questions.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,13 @@ async def delete(question_id: str):
@router.put("/{question_id}", response_description="Update question with specified id", response_model=QuestionModel)
async def update_question(question_id: str, question_data: UpdateQuestionModel):
updated_question = await update_question_by_id(question_id, question_data)

if updated_question is None:
raise HTTPException(status_code=404, detail="Question with this id does not exist.")

if updated_question == "duplicate_title":
raise HTTPException(status_code=409, detail="A question with this title already exists.")

return updated_question


Expand Down

0 comments on commit b8c0ae6

Please sign in to comment.