Skip to content

Commit

Permalink
feat: search stations api (#147)
Browse files Browse the repository at this point in the history
  • Loading branch information
gsarrco authored Nov 1, 2023
2 parents 24ad3ed + 2a6c63e commit 64c7408
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
8 changes: 8 additions & 0 deletions server/base/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ class Station(Base):
source: Mapped[str] = mapped_column(server_default='treni')
stops = relationship('Stop', back_populates='station', cascade='all, delete-orphan')

def as_dict(self):
return {
'id': self.id,
'name': self.name,
'lat': self.lat,
'lon': self.lon,
'source': self.source
}

class Stop(Base):
__tablename__ = 'stops'
Expand Down
13 changes: 11 additions & 2 deletions server/routes.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from sqlalchemy import text
from starlette.requests import Request
from starlette.responses import Response
from starlette.responses import Response, JSONResponse
from starlette.routing import Route

from server.sources import sources
Expand All @@ -26,6 +26,15 @@ async def home(request: Request) -> Response:
return Response(text_response)


async def search_stations(request: Request) -> Response:
query = request.query_params.get('q', '')
limit = int(request.query_params.get('limit', 4))
limit = max(1, min(limit, 10))
stations, count = sources['aut'].search_stops(name=query, all_sources=True, limit=limit)
return JSONResponse([station.as_dict() for station in stations])


routes = [
Route("/", home)
Route("/", home),
Route("/search/stations", search_stations)
]

0 comments on commit 64c7408

Please sign in to comment.