upsert instead of create
This commit is contained in:
parent
4e249d6f1b
commit
ece53f00db
|
|
@ -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")
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user