upsert instead of create

This commit is contained in:
Robert 2024-02-25 16:25:54 +07:00
parent 4e249d6f1b
commit ece53f00db
No known key found for this signature in database
GPG Key ID: F631C7FD957D5F22
2 changed files with 12 additions and 8 deletions

View File

@ -8,17 +8,18 @@ from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException
router = APIRouter(prefix="/chain")
ChainRepositoryDependency = Annotated[ChainRepository, Depends(get_chain_repository)]
@router.post("/")
async def chain_create_controller(
async def chain_upsert_controller(
chain: Chain,
chain_repository: Annotated[ChainRepository, Depends(get_chain_repository)],
chain_repository: ChainRepositoryDependency,
):
try:
created_chain = await chain_repository.create(chain)
return created_chain
upserted_chain = await chain_repository.upsert(chain)
return upserted_chain
except Exception:
logger.exception(f"Error during chain creation {chain.model_dump_json()}")
return HTTPException(status_code=500, detail="Error during chain creation")
logger.exception(f"Error during chain upsert {chain.model_dump_json()}")
return HTTPException(status_code=500, detail="Error during chain upsert")

View File

@ -7,6 +7,9 @@ class ChainRepository:
def __init__(self, database: Database):
self.collection = database.get_collection("chains")
async def create(self, chain: Chain) -> Chain:
await self.collection.insert_one(chain.model_dump(by_alias=True))
async def upsert(self, chain: Chain) -> Chain:
await self.collection.replace_one(
{"_id": chain.id}, chain.model_dump(by_alias=True), upsert=True
)
return chain