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
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
|
|
||||||
router = APIRouter(prefix="/chain")
|
router = APIRouter(prefix="/chain")
|
||||||
|
ChainRepositoryDependency = Annotated[ChainRepository, Depends(get_chain_repository)]
|
||||||
|
|
||||||
|
|
||||||
@router.post("/")
|
@router.post("/")
|
||||||
async def chain_create_controller(
|
async def chain_upsert_controller(
|
||||||
chain: Chain,
|
chain: Chain,
|
||||||
chain_repository: Annotated[ChainRepository, Depends(get_chain_repository)],
|
chain_repository: ChainRepositoryDependency,
|
||||||
):
|
):
|
||||||
try:
|
try:
|
||||||
created_chain = await chain_repository.create(chain)
|
upserted_chain = await chain_repository.upsert(chain)
|
||||||
return created_chain
|
return upserted_chain
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
logger.exception(f"Error during chain creation {chain.model_dump_json()}")
|
logger.exception(f"Error during chain upsert {chain.model_dump_json()}")
|
||||||
return HTTPException(status_code=500, detail="Error during chain creation")
|
return HTTPException(status_code=500, detail="Error during chain upsert")
|
||||||
|
|
|
||||||
|
|
@ -7,6 +7,9 @@ class ChainRepository:
|
||||||
def __init__(self, database: Database):
|
def __init__(self, database: Database):
|
||||||
self.collection = database.get_collection("chains")
|
self.collection = database.get_collection("chains")
|
||||||
|
|
||||||
async def create(self, chain: Chain) -> Chain:
|
async def upsert(self, chain: Chain) -> Chain:
|
||||||
await self.collection.insert_one(chain.model_dump(by_alias=True))
|
await self.collection.replace_one(
|
||||||
|
{"_id": chain.id}, chain.model_dump(by_alias=True), upsert=True
|
||||||
|
)
|
||||||
|
|
||||||
return chain
|
return chain
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue
Block a user