Skip to content

Commit

Permalink
pagination data models
Browse files Browse the repository at this point in the history
  • Loading branch information
bozzelliandrea authored Jan 14, 2024
1 parent 0764aa5 commit fe53595
Showing 1 changed file with 52 additions and 2 deletions.
54 changes: 52 additions & 2 deletions abstract_data_layer/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,18 @@
"""
from abc import abstractmethod
from datetime import datetime
from typing import TypeVar, Generic, Protocol
from enum import Enum
from typing import TypeVar, Generic, Protocol, List

ID = TypeVar('ID')
T = TypeVar('T')


class Entity(Protocol):
createDate: datetime
updateDate: datetime


class CRUD(Generic[T, ID]):

@abstractmethod
Expand All @@ -39,4 +42,51 @@ def create(self, obj: T) -> T:

@abstractmethod
def update(self, obj: T) -> T:
pass
pass


class SortOrder(Enum):
ASC = 1
DESC = 2


class Sorting(Generic[T]):
def __init__(self, field: str, order: SortOrder):
self.order = order
if not hasattr(T, field):
raise KeyError(f"Field {field} doesn't exists in object")

@staticmethod
def asc(field: str) -> 'Sorting':
return Sorting(field, SortOrder.ASC)

@staticmethod
def desc(field: str) -> 'Sorting':
return Sorting(field, SortOrder.DESC)


class PageRequest(Generic[T]):

def __init__(self, page: int = 0, size: int = 20, query: T = None, sorting: SortOrder[T] = None):
self.page = page
self.size = size
self.query = query
self.sorting = sorting

@staticmethod
def on(page: int) -> 'PageRequest':
return PageRequest(page)


class PageResponse(Generic[T]):

def __init__(self, elements: List[T] = None,
page: int = 0,
page_size: int = 0,
total_pages: int = 0,
total_size: int = 0):
self.elements = elements if elements is not None else []
self.page = page
self.page_size = page_size
self.total_pages = total_pages
self.total_size = total_size

0 comments on commit fe53595

Please sign in to comment.