Files
ai-char-bot/repos/assets_repo.py
2026-02-03 14:20:22 +03:00

40 lines
1.4 KiB
Python

from typing import List
from bson import ObjectId
from motor.motor_asyncio import AsyncIOMotorClient
from models.Asset import Asset
class AssetsRepo:
def __init__(self, client: AsyncIOMotorClient, db_name="bot_db"):
self.collection = client[db_name]["assets"]
async def save_asset(self, asset: Asset) -> Asset:
res = await self.collection.insert_one(asset.model_dump())
asset.id = res.inserted_id
return asset
async def get_assets(self, limit: int = 10, offset: int = 0) -> List[Asset]:
res = await self.collection.find({},{"data":0}).sort("created_at", -1).skip(offset).limit(limit).to_list(None)
assets = []
for doc in res:
# Конвертируем ObjectId в строку и кладем в поле id
doc["id"] = str(doc.pop("_id"))
# Создаем объект
assets.append(Asset(**doc))
return assets
async def get_asset(self, asset_id: str) -> Asset:
res = await self.collection.find_one({"_id": ObjectId(asset_id)})
res["id"] = str(res.pop("_id"))
return Asset(**res)
async def update_asset(self, asset_id: str, asset: Asset):
if not asset.id:
raise Exception(f"Asset ID not found: {asset_id}")
await self.collection.update_one({"_id": ObjectId(asset_id)}, {"$set": asset.model_dump()})