manage.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # -*- coding: utf-8 -*-
  2. # (c) Nelen & Schuurmans
  3. from typing import Any
  4. from typing import Generic
  5. from typing import List
  6. from typing import Optional
  7. from typing import Type
  8. from typing import TypeVar
  9. from clean_python.base.domain.pagination import Page
  10. from clean_python.base.domain.pagination import PageOptions
  11. from clean_python.base.domain.repository import Repository
  12. from clean_python.base.domain.root_entity import RootEntity
  13. from clean_python.base.infrastructure.gateway import Filter
  14. from clean_python.base.infrastructure.gateway import Json
  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: int) -> 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: int, values: Json) -> T:
  34. return await self.repo.update(id, values)
  35. async def destroy(self, id: int) -> 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)