Files
bakery-ia/gateway/app/routes/data.py
Urtzi Alfaro 592a810762 Fix issues
2025-07-18 11:51:43 +02:00

71 lines
3.0 KiB
Python

# ================================================================
# gateway/app/routes/data.py
# ================================================================
"""Data service routes for API Gateway"""
from fastapi import APIRouter, Request, Depends, HTTPException
from fastapi.responses import StreamingResponse
import httpx
import structlog
from app.core.config import settings
from app.core.auth import verify_token
logger = structlog.get_logger()
router = APIRouter()
@router.api_route("/sales/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def proxy_sales(request: Request, path: str, current_user: dict = Depends(verify_token)):
"""Proxy sales data requests to data service"""
return await _proxy_request(request, f"/api/v1/sales/{path}")
@router.api_route("/weather/{path:path}", methods=["GET", "POST"])
async def proxy_weather(request: Request, path: str, current_user: dict = Depends(verify_token)):
"""Proxy weather requests to data service"""
return await _proxy_request(request, f"/api/v1/weather/{path}")
@router.api_route("/traffic/{path:path}", methods=["GET", "POST"])
async def proxy_traffic(request: Request, path: str, current_user: dict = Depends(verify_token)):
"""Proxy traffic requests to data service"""
return await _proxy_request(request, f"/api/v1/traffic/{path}")
async def _proxy_request(request: Request, target_path: str):
"""Proxy request to data service"""
try:
url = f"{settings.DATA_SERVICE_URL}{target_path}"
# Forward headers (including auth)
headers = dict(request.headers)
headers.pop("host", None) # Remove host header
# Get request body if present
body = None
if request.method in ["POST", "PUT", "PATCH"]:
body = await request.body()
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.request(
method=request.method,
url=url,
params=request.query_params,
headers=headers,
content=body
)
# Return streaming response for large payloads
if int(response.headers.get("content-length", 0)) > 1024:
return StreamingResponse(
iter([response.content]),
status_code=response.status_code,
headers=dict(response.headers),
media_type=response.headers.get("content-type")
)
else:
return response.json() if response.headers.get("content-type", "").startswith("application/json") else response.content
except httpx.RequestError as e:
logger.error("Data service request failed", error=str(e))
raise HTTPException(status_code=503, detail="Data service unavailable")
except Exception as e:
logger.error("Unexpected error in data proxy", error=str(e))
raise HTTPException(status_code=500, detail="Internal server error")