manage.py 2.0 KB

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