An ebook/comic library service and web client
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.3 KiB

  1. """Model definitions for the api module."""
  2. from typing import Any, List, Optional, Dict, Type
  3. from flask_sqlalchemy import Pagination
  4. from atheneum import db
  5. # pylint: disable=too-few-public-methods
  6. class APIResponse:
  7. """Custom class to wrap api responses."""
  8. def __init__(self,
  9. payload: Any,
  10. status: int = 200,
  11. options: Optional[List[str]] = None) -> None:
  12. """Construct an APIResponse object."""
  13. self.payload = payload
  14. self.status = status
  15. self.options = options
  16. # pylint: disable=too-few-public-methods
  17. class BaseAPIMessage:
  18. """Base class for API responses."""
  19. def to_dict(self) -> Dict[str, Any]:
  20. """Abstract to_dict."""
  21. raise NotImplementedError('Not Implemented')
  22. # pylint: disable=too-few-public-methods
  23. class APIMessage(BaseAPIMessage):
  24. """Simple class to encapsulate response messages."""
  25. success: bool
  26. message: Optional[str]
  27. def __init__(self,
  28. success: bool,
  29. message: Optional[str]) -> None:
  30. """Construct an APIMessage."""
  31. self.success = success
  32. self.message = message
  33. def to_dict(self) -> Dict[str, Any]:
  34. """Serialize an APIMessage to a dict."""
  35. obj: Dict[str, Any] = {
  36. 'success': self.success
  37. }
  38. if self.message is not None:
  39. obj['message'] = self.message
  40. return obj
  41. # pylint: disable=too-few-public-methods
  42. class APIPage(BaseAPIMessage):
  43. """Simple page response."""
  44. def __init__(self,
  45. page: int,
  46. total_count: int,
  47. last_page: int,
  48. items: List[Type[db.Model]]) -> None:
  49. """Construct and APIPage."""
  50. self.page = page
  51. self.count = len(items)
  52. self.total_count = total_count
  53. self.last_page = last_page
  54. self.items = items
  55. def to_dict(self) -> Dict[str, Any]:
  56. """Serialize an APIPage."""
  57. return {
  58. 'page': self.page,
  59. 'count': self.count,
  60. 'totalCount': self.total_count,
  61. 'lastPage': self.last_page,
  62. 'items': self.items
  63. }
  64. @staticmethod
  65. def from_page(page: Pagination) -> 'APIPage':
  66. """Create an APIPage from a Pagination object."""
  67. return APIPage(page.page, page.total, page.pages, page.items)