34 lines
1.1 KiB
Python
34 lines
1.1 KiB
Python
from bson import ObjectId
|
|
from typing import List, Optional
|
|
from models import QuizEntity
|
|
|
|
|
|
class QuizRepository:
|
|
def __init__(self, db):
|
|
self.collection = db.quiz
|
|
|
|
def create(self, quiz: QuizEntity) -> str:
|
|
quiz_dict = quiz.dict(by_alias=True, exclude_none=True)
|
|
result = self.collection.insert_one(quiz_dict)
|
|
return str(result.inserted_id)
|
|
|
|
def get_by_id(self, quiz_id: str) -> Optional[QuizEntity]:
|
|
data = self.collection.find_one({"_id": ObjectId(quiz_id)})
|
|
if data:
|
|
return QuizEntity(**data)
|
|
return None
|
|
|
|
def get_all(self, skip: int = 0, limit: int = 10) -> List[QuizEntity]:
|
|
cursor = self.collection.find().skip(skip).limit(limit)
|
|
return [QuizEntity(**doc) for doc in cursor]
|
|
|
|
def update(self, quiz_id: str, update_data: dict) -> bool:
|
|
result = self.collection.update_one(
|
|
{"_id": ObjectId(quiz_id)}, {"$set": update_data}
|
|
)
|
|
return result.modified_count > 0
|
|
|
|
def delete(self, quiz_id: str) -> bool:
|
|
result = self.collection.delete_one({"_id": ObjectId(quiz_id)})
|
|
return result.deleted_count > 0
|