73 lines
2.5 KiB
Python
73 lines
2.5 KiB
Python
from beanie import PydanticObjectId
|
|
from fastapi import APIRouter, Depends, HTTPException
|
|
|
|
from hub.auth import get_current_user
|
|
from hub.firm import Firm, FirmRead, FirmCreate, FirmUpdate
|
|
|
|
model = Firm
|
|
model_read = FirmRead
|
|
model_create = FirmCreate
|
|
model_update = FirmUpdate
|
|
|
|
router = APIRouter()
|
|
|
|
@router.post("/", response_description="{} added to the database".format(model.__name__))
|
|
async def create(item: model_create, user=Depends(get_current_user)) -> model_read:
|
|
exists = await Firm.find_one({"name": item.name, "instance": item.instance})
|
|
if exists:
|
|
raise HTTPException(status_code=400, detail="Firm already exists")
|
|
|
|
record = model(created_by=user.id, updated_by=user.id, owner=user.id, **item.model_dump())
|
|
o = await record.create()
|
|
user.firms.append(o.id)
|
|
user.save()
|
|
return model_read(**o.model_dump())
|
|
|
|
@router.get("/{id}", response_description="{} record retrieved".format(model.__name__))
|
|
async def read_id(id: PydanticObjectId, user=Depends(get_current_user)) -> model_read:
|
|
item = await model.get(id)
|
|
return model_read(**item.model_dump())
|
|
|
|
|
|
@router.put("/{id}", response_description="{} record updated".format(model.__name__))
|
|
async def update(id: PydanticObjectId, req: model_update, user=Depends(get_current_user)) -> model_read:
|
|
item = await model.get(id)
|
|
if not item:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="{} record not found!".format(model.__name__)
|
|
)
|
|
|
|
if item.owner != user.id:
|
|
raise HTTPException(
|
|
status_code=403,
|
|
detail="Insufficient credentials to modify {} record".format(model.__name__)
|
|
)
|
|
|
|
req = {k: v for k, v in req.model_dump().items() if v is not None}
|
|
update_query = {"$set": {
|
|
field: value for field, value in req.items()
|
|
}}
|
|
|
|
await item.update(update_query)
|
|
return model_read(**item.dict())
|
|
|
|
@router.delete("/{id}", response_description="{} record deleted from the database".format(model.__name__))
|
|
async def delete(id: PydanticObjectId, user=Depends(get_current_user)) -> dict:
|
|
item = await model.get(id)
|
|
if not item:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="{} record not found!".format(model.__name__)
|
|
)
|
|
if item.owner != user.id:
|
|
raise HTTPException(
|
|
status_code=403,
|
|
detail="Insufficient credentials delete {} record".format(model.__name__)
|
|
)
|
|
|
|
await item.delete()
|
|
return {
|
|
"message": "{} deleted successfully".format(model.__name__)
|
|
}
|