From c4f01cd3f2073a085180ece3698f3c49e3f033c2 Mon Sep 17 00:00:00 2001 From: april Date: Tue, 2 Jan 2024 11:08:34 -0600 Subject: [PATCH] Add flight sorting --- api/database/flights.py | 8 +++++--- api/routes/flights.py | 9 +++++---- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/api/database/flights.py b/api/database/flights.py index 24e9e00..5a6f5fc 100644 --- a/api/database/flights.py +++ b/api/database/flights.py @@ -10,19 +10,21 @@ from schemas.flight import FlightConciseSchema, FlightDisplaySchema, FlightCreat logger = logging.getLogger("api") -async def retrieve_flights(user: str = "") -> list[FlightConciseSchema]: +async def retrieve_flights(user: str = "", sort: str = "date", order: int = -1) -> list[FlightConciseSchema]: """ Retrieve a list of flights, optionally filtered by user :param user: User to filter flights by + :param sort: Parameter to sort results by + :param order: Sort order :return: List of flights """ flights = [] if user == "": - async for flight in flight_collection.find(): + async for flight in flight_collection.find().sort({sort: order}): flights.append(FlightConciseSchema(**flight_display_helper(flight))) else: - async for flight in flight_collection.find({"user": ObjectId(user)}): + async for flight in flight_collection.find({"user": ObjectId(user)}).sort({sort: order}): flights.append(FlightConciseSchema(**flight_display_helper(flight))) return flights diff --git a/api/routes/flights.py b/api/routes/flights.py index 8ac71f2..4070f1d 100644 --- a/api/routes/flights.py +++ b/api/routes/flights.py @@ -15,26 +15,27 @@ logger = logging.getLogger("flights") @router.get('/', summary="Get flights logged by the currently logged-in user", status_code=200, response_model=list[FlightConciseSchema]) -async def get_flights(user: UserDisplaySchema = Depends(get_current_user)) -> list[FlightConciseSchema]: +async def get_flights(user: UserDisplaySchema = Depends(get_current_user), sort: str = "date", order: int = -1) -> list[ + FlightConciseSchema]: """ Get a list of the flights logged by the currently logged-in user :return: List of flights """ # l = get_flight_list(filters=[[{"field": "user", "operator": "eq", "value": user.id}]]) - flights = await db.retrieve_flights(user.id) + flights = await db.retrieve_flights(user.id, sort, order) return flights @router.get('/all', summary="Get all flights logged by all users", status_code=200, dependencies=[Depends(admin_required)], response_model=list[FlightConciseSchema]) -async def get_all_flights() -> list[FlightConciseSchema]: +async def get_all_flights(sort: str = "date", order: int = -1) -> list[FlightConciseSchema]: """ Get a list of all flights logged by any user :return: List of flights """ - flights = await db.retrieve_flights() + flights = await db.retrieve_flights(sort, order) return flights