54 lines
2.2 KiB
Python
54 lines
2.2 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, with_data: bool = True) -> Asset:
|
|
res = await self.collection.find_one({"_id": ObjectId(asset_id)},
|
|
{"_id": 1, "name": 1, "type": 1, "tg_doc_file_id": 1,
|
|
"data": 0 if not with_data else 1})
|
|
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()})
|
|
|
|
async def set_tg_photo_file_id(self, asset_id: str, tg_photo_file_id: str):
|
|
await self.collection.update_one({"_id": ObjectId(asset_id)}, {"$set": {"tg_photo_file_id": tg_photo_file_id}})
|
|
|
|
async def get_assets_by_char_id(self, character_id: str, limit: int = 10, offset: int = 0) -> List[Asset]:
|
|
docs = await self.collection.find({"linked_char_id": character_id},
|
|
{"data": 0}, sort=[("created_at", -1)]).limit(limit).skip(offset).to_list(
|
|
None)
|
|
assets = []
|
|
for doc in docs:
|
|
doc["id"] = str(doc.pop("_id"))
|
|
assets.append(Asset(**doc))
|
|
return assets
|