Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: add pagination #49

Merged
merged 12 commits into from
May 15, 2024
54 changes: 38 additions & 16 deletions app/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,28 +359,50 @@ def create_ticket(ticket: TicketCreate) -> Ticket:
return _create_ticket(ticket)


def _get_ticket(status: TicketStatus | None, type_: IssueType | None):
"""Get tickets with optional filters."""
query = TicketModel.select()

if status is not None:
query = query.where(TicketModel.status == status)

if type_ is not None:
query = query.where(TicketModel.type == type_)

with db:
return list(query.dicts())


@api_v1_router.get("/tickets")
def get_tickets(status: TicketStatus | None = None, type_: IssueType | None = None):
def get_tickets(
status: TicketStatus | None = None,
type_: IssueType | None = None,
page: int = 1,
page_size: int = 10,
):
"""Get all tickets.

This function is used to get all tickets with status open.
"""
with db:
return _get_ticket(status, type_)
offset = (page - 1) * page_size
# Get the total number of opend and type tickets
Valimp marked this conversation as resolved.
Show resolved Hide resolved
count = (
TicketModel.select()
.where(
(TicketModel.status == status if status else True)
& (TicketModel.type == type_ if type_ else True)
)
.count()
)
max_page = count // page_size + int(count % page_size != 0)
if max_page * page_size < count:
Valimp marked this conversation as resolved.
Show resolved Hide resolved
max_page += 1
if page > max_page:
raise HTTPException(
status_code=404,
detail=f"Page {page} not found. Max page is {max_page}",
)
return {
"tickets": list(
TicketModel.select()
.where(
(TicketModel.status == status if status else True)
& (TicketModel.type == type_ if type_ else True)
)
.order_by(TicketModel.created_at.desc())
.offset(offset)
.limit(page_size)
.dicts()
),
"max_page": max_page,
}


@api_v1_router.get("/tickets/{ticket_id}")
Expand Down