manage.py 1.8 KB

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