manage.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # (c) Nelen & Schuurmans
  2. from typing import Any
  3. from typing import Generic
  4. from typing import List
  5. from typing import Optional
  6. from typing import Type
  7. from typing import TypeVar
  8. from clean_python.base.domain import Filter
  9. from clean_python.base.domain import Json
  10. from clean_python.base.domain import Page
  11. from clean_python.base.domain import PageOptions
  12. from clean_python.base.domain import Repository
  13. from clean_python.base.domain import RootEntity
  14. T = TypeVar("T", bound=RootEntity)
  15. __all__ = ["Manage"]
  16. class Manage(Generic[T]):
  17. repo: Repository[T]
  18. entity: Type[T]
  19. def __init__(self, repo: Optional[Repository[T]] = None):
  20. assert repo is not None
  21. self.repo = repo
  22. def __init_subclass__(cls) -> None:
  23. (base,) = cls.__orig_bases__ # type: ignore
  24. (entity,) = base.__args__
  25. assert issubclass(entity, RootEntity)
  26. super().__init_subclass__()
  27. cls.entity = entity
  28. async def retrieve(self, id: int) -> T:
  29. return await self.repo.get(id)
  30. async def create(self, values: Json) -> T:
  31. return await self.repo.add(values)
  32. async def update(self, id: int, values: Json) -> T:
  33. return await self.repo.update(id, values)
  34. async def destroy(self, id: int) -> bool:
  35. return await self.repo.remove(id)
  36. async def list(self, params: Optional[PageOptions] = None) -> Page[T]:
  37. return await self.repo.all(params)
  38. async def by(
  39. self, key: str, value: Any, params: Optional[PageOptions] = None
  40. ) -> Page[T]:
  41. return await self.repo.by(key, value, params=params)
  42. async def filter(
  43. self, filters: List[Filter], params: Optional[PageOptions] = None
  44. ) -> Page[T]:
  45. return await self.repo.filter(filters, params=params)
  46. async def count(self, filters: List[Filter]) -> int:
  47. return await self.repo.count(filters)
  48. async def exists(self, filters: List[Filter]) -> bool:
  49. return await self.repo.exists(filters)