55 lines
2.1 KiB
Python
55 lines
2.1 KiB
Python
from typing import List, Optional
|
|
|
|
from bson import ObjectId
|
|
from motor.motor_asyncio import AsyncIOMotorClient
|
|
|
|
from models.Inspiration import Inspiration
|
|
|
|
|
|
class InspirationRepo:
|
|
def __init__(self, client: AsyncIOMotorClient, db_name="bot_db"):
|
|
self.collection = client[db_name]["inspirations"]
|
|
|
|
async def create_inspiration(self, inspiration: Inspiration) -> str:
|
|
res = await self.collection.insert_one(inspiration.model_dump(exclude={"id"}))
|
|
return str(res.inserted_id)
|
|
|
|
async def get_inspiration(self, inspiration_id: str) -> Optional[Inspiration]:
|
|
res = await self.collection.find_one({"_id": ObjectId(inspiration_id)})
|
|
if res:
|
|
res["id"] = str(res.pop("_id"))
|
|
return Inspiration(**res)
|
|
return None
|
|
|
|
async def get_inspirations(self, project_id: Optional[str] = None, created_by: Optional[str] = None, limit: int = 20, offset: int = 0) -> List[Inspiration]:
|
|
query = {}
|
|
if project_id:
|
|
query["project_id"] = project_id
|
|
if created_by:
|
|
query["created_by"] = created_by
|
|
|
|
cursor = self.collection.find(query).sort("created_at", -1).skip(offset).limit(limit)
|
|
inspirations = []
|
|
async for doc in cursor:
|
|
doc["id"] = str(doc.pop("_id"))
|
|
inspirations.append(Inspiration(**doc))
|
|
return inspirations
|
|
|
|
async def count_inspirations(self, project_id: Optional[str] = None, created_by: Optional[str] = None) -> int:
|
|
query = {}
|
|
if project_id:
|
|
query["project_id"] = project_id
|
|
if created_by:
|
|
query["created_by"] = created_by
|
|
return await self.collection.count_documents(query)
|
|
|
|
async def update_inspiration(self, inspiration: Inspiration):
|
|
await self.collection.update_one(
|
|
{"_id": ObjectId(inspiration.id)},
|
|
{"$set": inspiration.model_dump(exclude={"id"})}
|
|
)
|
|
|
|
async def delete_inspiration(self, inspiration_id: str) -> bool:
|
|
res = await self.collection.delete_one({"_id": ObjectId(inspiration_id)})
|
|
return res.deleted_count > 0
|