Add sorting
This commit is contained in:
parent
dc0d2acf53
commit
6b458654a7
@ -1,9 +1,9 @@
|
||||
from typing import Annotated
|
||||
from typing import Annotated, Literal
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Depends
|
||||
from sqlalchemy.ext.asyncio.session import AsyncSession
|
||||
from sqlmodel import select
|
||||
from sqlmodel import asc, desc, select
|
||||
|
||||
from ..models.house import House
|
||||
from ..providers.db_provider import get_session
|
||||
@ -13,8 +13,19 @@ class HouseRepository:
|
||||
def __init__(self, session: Annotated[AsyncSession, Depends(get_session)]) -> None:
|
||||
self.session = session
|
||||
|
||||
async def get_all(self, limit: int = 100, offset: int = 0) -> list[House]:
|
||||
statement = select(House).offset(offset).limit(limit)
|
||||
async def get_all(
|
||||
self,
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
order_by: Literal["PRICE"] = "PRICE",
|
||||
sort_order: Literal["ASC", "DESC"] = "DESC",
|
||||
) -> list[House]:
|
||||
sorter = desc if sort_order == "DESC" else asc
|
||||
|
||||
statement = (
|
||||
select(House).offset(offset).limit(limit).order_by(sorter(House.price))
|
||||
)
|
||||
|
||||
result = await self.session.execute(statement)
|
||||
return result.scalars().all()
|
||||
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
from typing import Annotated
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
@ -48,10 +48,14 @@ async def create_house(
|
||||
@router.get("")
|
||||
async def get_all_houses(
|
||||
house_repository: Annotated[HouseRepository, Depends()],
|
||||
order_by: Literal["PRICE"] = "PRICE",
|
||||
sort_order: Literal["ASC", "DESC"] = "DESC",
|
||||
limit: int = 100,
|
||||
offset: int = 0,
|
||||
) -> HousesListResponse:
|
||||
all_houses = await house_repository.get_all(offset=offset, limit=limit)
|
||||
all_houses = await house_repository.get_all(
|
||||
offset=offset, limit=limit, order_by=order_by, sort_order=sort_order
|
||||
)
|
||||
|
||||
house_responses = [
|
||||
HouseResponse(
|
||||
@ -64,6 +68,5 @@ async def get_all_houses(
|
||||
)
|
||||
for house in all_houses
|
||||
]
|
||||
print(house_responses)
|
||||
|
||||
return HousesListResponse(houses=house_responses)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user