+ assets
This commit is contained in:
39
repos/assets_repo.py
Normal file
39
repos/assets_repo.py
Normal file
@@ -0,0 +1,39 @@
|
||||
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()})
|
||||
Reference in New Issue
Block a user