Skip to content

Commit

Permalink
better pagination sort key handle
Browse files Browse the repository at this point in the history
  • Loading branch information
wuttinanhi committed Sep 30, 2022
1 parent 42b7aff commit d76c3e9
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 13 deletions.
6 changes: 4 additions & 2 deletions mock/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def mock():
parking_lot_2 = ParkingLotService.add("Floor 2", True)
parking_lot_3 = ParkingLotService.add("Floor 3", False)

for _ in range(50):
for i in range(1, 50):
# mock reservation
reservation = ReservationService.create_reservation(
user, car_1, parking_lot_1, datetime.utcnow()
Expand All @@ -62,7 +62,9 @@ def mock():
)

# create invoice
PaymentService.create_invoice(reservation)
invoice = PaymentService.create_invoice(reservation)
invoice.charge_amount = i * 10
PaymentService.update_invoice(invoice)

# try:
# PaymentService.setup_payment()
Expand Down
24 changes: 18 additions & 6 deletions pagination/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@

from flask import Request
from marshmallow import Schema, fields, validate
from sqlalchemy import text
from sqlalchemy import desc
from sqlalchemy.orm.query import Query
from util.validate_request import ValidateRequest
from werkzeug.exceptions import BadRequest


class PaginationSortOptions(Enum):
Expand All @@ -19,9 +20,18 @@ def __str__(self):
return str(self.value)


def create_order_by(model, key: str, sort: PaginationSortOptions):
if hasattr(model, key):
result = model.__dict__.get(key)
if sort == PaginationSortOptions.DESC:
result = desc(result)
return result
raise BadRequest(f"Invalid order by key!: {key}")


class PaginationOptions(Schema):
page = fields.Integer(required=True, validate=validate.Range(min=1))
limit = fields.Integer(required=True, validate=validate.Range(min=1))
limit = fields.Integer(required=True, validate=validate.Range(min=1, max=100))
sort = fields.Integer(required=True, validate=validate.Range(min=0, max=1))
order_by = fields.String(required=True)

Expand All @@ -34,7 +44,6 @@ def create_pagination_options_from_request(request: Request):
options.limit = int(data.limit)
options.order_by = data.order_by


if int(data.sort) == 1:
options.sort = PaginationSortOptions.DESC
else:
Expand All @@ -55,7 +64,8 @@ def create_pagination_options(


class Pagination:
def __init__(self, query: Query) -> None:
def __init__(self, model, query: Query) -> None:
self.__model = model
self.__query = query

def set_options(self, opt: PaginationOptions):
Expand All @@ -69,11 +79,13 @@ def set_options(self, opt: PaginationOptions):
):
self.__sort = opt.sort
else:
raise Exception(f"Invalid pagination sorting option!: {opt.sort}")
raise BadRequest(f"Invalid pagination sorting option!: {opt.sort}")

def result(self):
return (
self.__query.order_by(text(f"{self.__order_by} {self.__sort}"))
self.__query.order_by(
create_order_by(self.__model, self.__order_by, self.__sort)
)
.offset(self.__offset)
.limit(self.__limit)
.all()
Expand Down
2 changes: 1 addition & 1 deletion payment/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def get_invoice_by_reservation(reservation: Reservation) -> Invoice:
@staticmethod
def paginate_user_invoice(user: User, options: PaginationOptions):
query = Invoice.query.filter(Invoice.user_id == user.id)
pagination = Pagination(query)
pagination = Pagination(Invoice, query)
pagination.set_options(options)
return pagination.result()

Expand Down
8 changes: 4 additions & 4 deletions thunder-tests/thunderclient.json
Original file line number Diff line number Diff line change
Expand Up @@ -264,11 +264,11 @@
"colId": "e9e3d3d8-d79c-43e7-b6ea-dbb24aa38d46",
"containerId": "",
"name": "user_invoice",
"url": "{{BASE_API_URL}}/payment/user_invoice?page=1&limit=5&sort=0&order_by=id",
"url": "{{BASE_API_URL}}/payment/user_invoice?page=1&limit=10&sort=0&order_by=charge_amount",
"method": "GET",
"sortNum": 30000,
"created": "2022-09-24T22:50:51.701Z",
"modified": "2022-09-30T07:36:59.534Z",
"modified": "2022-09-30T17:41:02.909Z",
"headers": [],
"params": [
{
Expand All @@ -278,7 +278,7 @@
},
{
"name": "limit",
"value": "5",
"value": "10",
"isPath": false
},
{
Expand All @@ -288,7 +288,7 @@
},
{
"name": "order_by",
"value": "id",
"value": "charge_amount",
"isPath": false
}
],
Expand Down

0 comments on commit d76c3e9

Please sign in to comment.