repository.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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 typing import Union
  9. from .exceptions import DoesNotExist
  10. from .filter import Filter
  11. from .gateway import Gateway
  12. from .json import Json
  13. from .pagination import Page
  14. from .pagination import PageOptions
  15. from .root_entity import RootEntity
  16. T = TypeVar("T", bound=RootEntity)
  17. class Repository(Generic[T]):
  18. entity: Type[T]
  19. def __init__(self, gateway: Gateway):
  20. self.gateway = gateway
  21. def __init_subclass__(cls) -> None:
  22. (base,) = cls.__orig_bases__ # type: ignore
  23. (entity,) = base.__args__
  24. assert issubclass(entity, RootEntity)
  25. super().__init_subclass__()
  26. cls.entity = entity
  27. async def all(self, params: Optional[PageOptions] = None) -> Page[T]:
  28. return await self.filter([], params=params)
  29. async def by(
  30. self, key: str, value: Any, params: Optional[PageOptions] = None
  31. ) -> Page[T]:
  32. return await self.filter([Filter(field=key, values=[value])], params=params)
  33. async def filter(
  34. self, filters: List[Filter], params: Optional[PageOptions] = None
  35. ) -> Page[T]:
  36. records = await self.gateway.filter(filters, params=params)
  37. total = len(records)
  38. # when using pagination, we may need to do a count in the db
  39. # except in a typical 'first page' situation with few records
  40. if params is not None and not (params.offset == 0 and total < params.limit):
  41. total = await self.count(filters)
  42. return Page(
  43. total=total,
  44. limit=params.limit if params else None,
  45. offset=params.offset if params else None,
  46. items=[self.entity(**x) for x in records],
  47. )
  48. async def get(self, id: int) -> T:
  49. res = await self.gateway.get(id)
  50. if res is None:
  51. raise DoesNotExist("object", id)
  52. else:
  53. return self.entity(**res)
  54. async def add(self, item: Union[T, Json]) -> T:
  55. if isinstance(item, dict):
  56. item = self.entity.create(**item)
  57. created = await self.gateway.add(item.dict())
  58. return self.entity(**created)
  59. async def update(self, id: int, values: Json) -> T:
  60. if not values:
  61. return await self.get(id)
  62. updated = await self.gateway.update_transactional(
  63. id, lambda x: self.entity(**x).update(**values).dict()
  64. )
  65. return self.entity(**updated)
  66. async def upsert(self, item: T) -> T:
  67. values = item.dict()
  68. upserted = await self.gateway.upsert(values)
  69. return self.entity(**upserted)
  70. async def remove(self, id: int) -> bool:
  71. return await self.gateway.remove(id)
  72. async def count(self, filters: List[Filter]) -> int:
  73. return await self.gateway.count(filters)
  74. async def exists(self, filters: List[Filter]) -> bool:
  75. return await self.gateway.exists(filters)