internal_gateway.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # -*- coding: utf-8 -*-
  2. # (c) Nelen & Schuurmans
  3. from abc import abstractmethod, abstractproperty
  4. from typing import Generic, List, Optional, TypeVar
  5. from clean_python.base.domain.exceptions import BadRequest, DoesNotExist
  6. from clean_python.base.infrastructure.gateway import Filter
  7. from clean_python.base.application.manage import Manage
  8. from clean_python.base.domain.pagination import PageOptions
  9. from clean_python.base.domain.root_entity import RootEntity
  10. from clean_python.base.domain.value_object import ValueObject
  11. E = TypeVar("E", bound=RootEntity) # External
  12. T = TypeVar("T", bound=ValueObject) # Internal
  13. # don't subclass Gateway; Gateway makes Json objects
  14. class InternalGateway(Generic[E, T]):
  15. @abstractproperty
  16. def manage(self) -> Manage[E]:
  17. raise NotImplementedError()
  18. @abstractmethod
  19. def _map(self, obj: E) -> T:
  20. raise NotImplementedError()
  21. async def get(self, id: int) -> Optional[T]:
  22. try:
  23. result = await self.manage.retrieve(id)
  24. except DoesNotExist:
  25. return None
  26. else:
  27. return self._map(result)
  28. async def filter(
  29. self, filters: List[Filter], params: Optional[PageOptions] = None
  30. ) -> List[T]:
  31. page = await self.manage.filter(filters, params)
  32. return [self._map(x) for x in page.items]
  33. async def add(self, item: T) -> T:
  34. try:
  35. created = await self.manage.create(item.dict())
  36. except BadRequest as e:
  37. raise ValueError(e)
  38. return self._map(created)
  39. async def remove(self, id) -> bool:
  40. return await self.manage.destroy(id)
  41. async def count(self, filters: List[Filter]) -> int:
  42. return await self.manage.count(filters)
  43. async def exists(self, filters: List[Filter]) -> bool:
  44. return await self.manage.exists(filters)