65 lines
2.1 KiB
Python
65 lines
2.1 KiB
Python
from beanie import PydanticObjectId
|
|
|
|
from fastapi import APIRouter, HTTPException
|
|
from typing import TypeVar, List, Generic
|
|
|
|
|
|
T = TypeVar('T')
|
|
U = TypeVar('U')
|
|
V = TypeVar('V')
|
|
W = TypeVar('W')
|
|
|
|
|
|
def get_crud_router(model, model_create, model_read, model_update):
|
|
router = APIRouter()
|
|
|
|
@router.post("/", response_description="{} added to the database".format(model.__name__))
|
|
async def create(item: model_create) -> dict:
|
|
await item.validate_foreign_key()
|
|
o = await model(**item.dict()).create()
|
|
return {"message": "{} added successfully".format(model.__name__), "id": o}
|
|
|
|
@router.get("/{id}", response_description="{} record retrieved".format(model.__name__))
|
|
async def read_id(id: PydanticObjectId) -> model_read:
|
|
item = await model.get(id)
|
|
return item
|
|
|
|
@router.get("/", response_description="{} records retrieved".format(model.__name__))
|
|
async def read_list() -> List[model_read]:
|
|
item = await model.find_all().to_list()
|
|
return item
|
|
|
|
@router.put("/{id}", response_description="{} record updated".format(model.__name__))
|
|
async def update(id: PydanticObjectId, req: model_update) -> model_read:
|
|
req = {k: v for k, v in req.dict().items() if v is not None}
|
|
update_query = {"$set": {
|
|
field: value for field, value in req.items()
|
|
}}
|
|
|
|
item = await model.get(id)
|
|
if not item:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="{} record not found!".format(model.__name__)
|
|
)
|
|
|
|
await item.update(update_query)
|
|
return item
|
|
|
|
@router.delete("/{id}", response_description="{} record deleted from the database".format(model.__name__))
|
|
async def delete(id: PydanticObjectId) -> dict:
|
|
item = await model.get(id)
|
|
|
|
if not item:
|
|
raise HTTPException(
|
|
status_code=404,
|
|
detail="{} record not found!".format(model.__name__)
|
|
)
|
|
|
|
await item.delete()
|
|
return {
|
|
"message": "{} deleted successfully".format(model.__name__)
|
|
}
|
|
|
|
return router
|