product_response.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import typing
  2. import collections.abc
  3. from .product import product
  4. from .exception import not_ready_exception
  5. class product_response:
  6. def __new__(
  7. cls,
  8. target: product | typing.Iterable[product]
  9. ) -> list | dict:
  10. if isinstance(target, product):
  11. return cls.single(target)
  12. if isinstance(target, collections.abc.Iterable):
  13. return cls.collection(target)
  14. raise TypeError("Bad type for product response generator.")
  15. def single(target: product) -> dict:
  16. if not target.ready:
  17. raise not_ready_exception(target)
  18. return {
  19. "name": target.name,
  20. "description": target.description,
  21. "author": target.author,
  22. "image": target.image,
  23. "stock_count": target.stock_count,
  24. "barcode": target.barcode
  25. }
  26. def collection(targets: typing.Iterable[product]) -> list:
  27. result = list()
  28. for count in targets:
  29. if not isinstance(count, product):
  30. raise TypeError("Products iterable must contain products.")
  31. result.append(product_response.single(count))
  32. return result