from typing import Any, List
from beanie import PydanticObjectId
from pydantic import BaseModel
class DocumentHelper:
def __init__(self, modelMetaClass):
self.modelMetaClass = modelMetaClass
async def create(self, document) -> str:
document = await document.create()
return document.id
async def get(self, id : PydanticObjectId) -> Any:
document = await self.modelMetaClass.get(id)
if document:
return document
return False
async def getList(self) -> List[Any]:
documentList = await self.modelMetaClass.find_all().to_list()
return documentList
async def update(self, id : PydanticObjectId, updateModel : BaseModel) -> Any:
documentID = id
updateModelDictionary = updateModel.dict()
updateModelDictionary = {k : v for k, v in baseModelDictionary.items() if v is not None}
updateQuery = {"$set" : {field: value for field, value in updateModelDictionary.items()}}
document = await self.get(documentID)
if not document:
return False
await document.update(updateQuery)
return document
async def delete(self, id : PydanticObjectId) -> bool:
document = await self.get(id)
if not document:
return False
await document.delete()
return True
async def deleteAll(self):
await self.modelMetaClass.find_all().delete()