22 lines
679 B
Python
22 lines
679 B
Python
from typing import Optional
|
|
|
|
from fastapi import Query
|
|
from sqlalchemy import Select
|
|
|
|
from schemas.base import SortingSchema, SortDir
|
|
from utils.strings import camel_to_snake
|
|
|
|
|
|
async def sorting_parameters(
|
|
field: Optional[str] = Query(default=None, alias="sortingField"),
|
|
direction: Optional[SortDir] = Query(default=None, alias="sortingDirection"),
|
|
) -> SortingSchema:
|
|
return SortingSchema(field=camel_to_snake(field), direction=direction)
|
|
|
|
|
|
def apply_sorting(stmt: Select, cls: type, field: str, direction: SortDir) -> Select:
|
|
attr = getattr(cls, field)
|
|
if direction == "asc":
|
|
return stmt.order_by(attr.asc())
|
|
return stmt.order_by(attr.desc())
|