repository.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from typing import Protocol
  2. from app.domains.catalog.models import Product, ProductChangeLog, ProductVersion
  3. class CatalogRepository(Protocol):
  4. def save_product(self, product: Product) -> None: ...
  5. def list_products(self) -> list[Product]: ...
  6. def list_versions(self, product_id: str) -> list[ProductVersion]: ...
  7. def save_version(self, version: ProductVersion) -> None: ...
  8. def delete_version(self, version_id: str) -> None: ...
  9. def save_change_log(self, log: ProductChangeLog) -> None: ...
  10. def list_change_logs(self, product_id: str) -> list[ProductChangeLog]: ...
  11. class InMemoryCatalogRepository:
  12. def __init__(self) -> None:
  13. self._products: dict[str, Product] = {}
  14. self._versions: dict[str, list[ProductVersion]] = {}
  15. self._change_logs: list[ProductChangeLog] = []
  16. def save_product(self, product: Product) -> None:
  17. self._products[product.id] = product
  18. def save_version(self, version: ProductVersion) -> None:
  19. versions = self._versions.setdefault(version.product_id, [])
  20. for index, existing in enumerate(versions):
  21. if existing.id == version.id:
  22. versions[index] = version
  23. break
  24. else:
  25. versions.append(version)
  26. def list_products(self) -> list[Product]:
  27. return list(self._products.values())
  28. def list_versions(self, product_id: str) -> list[ProductVersion]:
  29. return list(self._versions.get(product_id, []))
  30. def delete_version(self, version_id: str) -> None:
  31. for product_id, versions in self._versions.items():
  32. self._versions[product_id] = [
  33. version for version in versions if version.id != version_id
  34. ]
  35. def save_change_log(self, log: ProductChangeLog) -> None:
  36. self._change_logs.append(log)
  37. def list_change_logs(self, product_id: str) -> list[ProductChangeLog]:
  38. return [log for log in self._change_logs if log.product_id == product_id]