Commit f1ac2f8e authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Add reverse-geocode endpoint to support 'locate me' on the soundmark map

GET /soundmarks/reverse-geocode?lat=&lon= mirrors the existing forward
/geocode proxy (same Nominatim server-side-proxy reasoning, same
business_admin+ gate) but for coordinates -> address instead of
address -> coordinates. Lets the location picker pre-fill its search
field from the browser's own location instead of just placing a pin
with no readable address next to it.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 00214e85
Pipeline #1117 passed with stage
in 3 minutes and 54 seconds
......@@ -334,6 +334,28 @@ async def geocode_address(q: str, current_user: User = Depends(get_current_busin
return {"status": "success", "results": results}
@router.get("/reverse-geocode")
async def reverse_geocode(lat: float, lon: float, current_user: User = Depends(get_current_business_admin)):
"""The inverse of /geocode - given coordinates (e.g. from the browser's "locate me"), looks
up a human-readable address to pre-fill the location picker's search field with. Same
server-side-proxy reasoning as /geocode (NOMINATIM_USER_AGENT)."""
try:
async with httpx.AsyncClient(timeout=10.0) as client:
res = await client.get(
"https://nominatim.openstreetmap.org/reverse",
params={"lat": lat, "lon": lon, "format": "jsonv2"},
headers={"User-Agent": NOMINATIM_USER_AGENT},
)
res.raise_for_status()
data = res.json()
except httpx.HTTPError as e:
logger.error(f"Nominatim reverse geocode request failed: {e}")
raise HTTPException(status_code=502, detail="Location lookup is temporarily unavailable")
if "error" in data:
return {"status": "success", "display_name": None}
return {"status": "success", "display_name": data.get("display_name")}
@router.get("/admin/users")
def list_users(
role: Optional[str] = None, db: Session = Depends(get_db), current_user: User = Depends(get_current_super_admin)
......
......@@ -807,3 +807,70 @@ def test_geocode_upstream_failure_returns_502(client, auth_as, mocker):
response = client.get("/soundmarks/geocode", params={"q": "Paris"}, headers=headers)
assert response.status_code == 502
# ---- Reverse geocode proxy ----
class _FakeReverseGeocodeAsyncClient:
"""Nominatim's /reverse returns a single object, not a list like /search - a distinct fake
from _FakeAsyncClient rather than reusing it, so the shape matches what the real endpoint
returns."""
last_request = None
def __init__(self, *args, **kwargs):
pass
async def __aenter__(self):
return self
async def __aexit__(self, *args):
return False
async def get(self, url, params=None, headers=None):
_FakeReverseGeocodeAsyncClient.last_request = {"url": url, "params": params, "headers": headers}
return _FakeGeocodeResponse({"display_name": "48 Rue de Rivoli, Paris, France", "lat": "48.8584", "lon": "2.2945"})
def test_reverse_geocode_proxies_nominatim_with_a_real_user_agent(client, auth_as, mocker):
headers, _ = auth_as(role="business_admin")
mocker.patch("src.api.routers.soundmarks.httpx.AsyncClient", _FakeReverseGeocodeAsyncClient)
response = client.get("/soundmarks/reverse-geocode", params={"lat": 48.8584, "lon": 2.2945}, headers=headers)
assert response.status_code == 200
assert response.json()["display_name"] == "48 Rue de Rivoli, Paris, France"
assert "User-Agent" in _FakeReverseGeocodeAsyncClient.last_request["headers"]
def test_reverse_geocode_requires_business_admin(client, auth_as):
headers, _ = auth_as()
response = client.get("/soundmarks/reverse-geocode", params={"lat": 1, "lon": 1}, headers=headers)
assert response.status_code == 403
def test_reverse_geocode_handles_nominatim_returning_no_match(client, auth_as, mocker):
headers, _ = auth_as(role="business_admin")
class _NoMatchClient(_FakeReverseGeocodeAsyncClient):
async def get(self, *args, **kwargs):
return _FakeGeocodeResponse({"error": "Unable to geocode"})
mocker.patch("src.api.routers.soundmarks.httpx.AsyncClient", _NoMatchClient)
response = client.get("/soundmarks/reverse-geocode", params={"lat": 0, "lon": 0}, headers=headers)
assert response.status_code == 200
assert response.json()["display_name"] is None
def test_reverse_geocode_upstream_failure_returns_502(client, auth_as, mocker):
headers, _ = auth_as(role="business_admin")
class _FailingClient(_FakeReverseGeocodeAsyncClient):
async def get(self, *args, **kwargs):
raise httpx.ConnectError("boom")
mocker.patch("src.api.routers.soundmarks.httpx.AsyncClient", _FailingClient)
response = client.get("/soundmarks/reverse-geocode", params={"lat": 1, "lon": 1}, headers=headers)
assert response.status_code == 502
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment