30 lines
1.0 KiB
Python
30 lines
1.0 KiB
Python
import pymongo
|
|
from uuid import UUID
|
|
from typing import List
|
|
from pydantic import TypeAdapter
|
|
|
|
from chain_service.database.database import Database
|
|
from chain_service.database.models.chain import Chain
|
|
|
|
|
|
class ChainRepository:
|
|
|
|
def __init__(self, database: Database):
|
|
self.collection = database.get_collection("chains")
|
|
|
|
async def upsert(self, chain: Chain) -> Chain:
|
|
query = {"_id": chain.id}
|
|
payload = chain.model_dump(by_alias=True)
|
|
await self.collection.replace_one(query, payload, upsert=True)
|
|
return chain
|
|
|
|
async def get_list(self) -> List[Chain]:
|
|
sort_order = ("lastModified", pymongo.DESCENDING)
|
|
chains = [chain async for chain in self.collection.find().sort(*sort_order)]
|
|
return TypeAdapter(List[Chain]).validate_python(chains)
|
|
|
|
async def get_by_id(self, chain_id: str) -> Chain | None:
|
|
query = {"_id": UUID(chain_id)}
|
|
chain = await self.collection.find_one(query)
|
|
return Chain.model_validate(chain) if chain else None
|