REFACTOR ALL APIs fix 1

This commit is contained in:
Urtzi Alfaro
2025-10-07 07:15:07 +02:00
parent 38fb98bc27
commit 7c72f83c51
47 changed files with 1821 additions and 270 deletions

View File

@@ -22,7 +22,7 @@ async def proxy_demo_service(path: str, request: Request):
"""
# Build the target URL
demo_service_url = settings.DEMO_SESSION_SERVICE_URL.rstrip('/')
target_url = f"{demo_service_url}/api/demo/{path}"
target_url = f"{demo_service_url}/api/v1/demo/{path}"
# Get request body
body = None

89
gateway/app/routes/pos.py Normal file
View File

@@ -0,0 +1,89 @@
"""
POS routes for API Gateway - Global POS endpoints
"""
from fastapi import APIRouter, Request, Response, HTTPException
from fastapi.responses import JSONResponse
import httpx
import logging
from app.core.config import settings
logger = logging.getLogger(__name__)
router = APIRouter()
# ================================================================
# GLOBAL POS ENDPOINTS (No tenant context required)
# ================================================================
@router.api_route("/supported-systems", methods=["GET", "OPTIONS"])
async def proxy_supported_systems(request: Request):
"""Proxy supported POS systems request to POS service"""
target_path = "/api/v1/pos/supported-systems"
return await _proxy_to_pos_service(request, target_path)
# ================================================================
# PROXY HELPER FUNCTIONS
# ================================================================
async def _proxy_to_pos_service(request: Request, target_path: str):
"""Proxy request to POS service"""
# Handle OPTIONS requests directly for CORS
if request.method == "OPTIONS":
return Response(
status_code=200,
headers={
"Access-Control-Allow-Origin": settings.CORS_ORIGINS_LIST,
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Tenant-ID",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Max-Age": "86400"
}
)
try:
url = f"{settings.POS_SERVICE_URL}{target_path}"
# Forward headers
headers = dict(request.headers)
headers.pop("host", None)
# Add query parameters
params = dict(request.query_params)
timeout_config = httpx.Timeout(
connect=30.0,
read=60.0,
write=30.0,
pool=30.0
)
async with httpx.AsyncClient(timeout=timeout_config) as client:
response = await client.request(
method=request.method,
url=url,
headers=headers,
params=params
)
# Handle different response types
if response.headers.get("content-type", "").startswith("application/json"):
try:
content = response.json()
except:
content = {"message": "Invalid JSON response from service"}
else:
content = response.text
return JSONResponse(
status_code=response.status_code,
content=content
)
except Exception as e:
logger.error(f"Unexpected error proxying to POS service {target_path}: {e}")
raise HTTPException(
status_code=500,
detail="Internal gateway error"
)

View File

@@ -17,10 +17,10 @@ router = APIRouter()
# SUBSCRIPTION ENDPOINTS - Direct routing to tenant service
# ================================================================
@router.api_route("/subscriptions/{tenant_id}/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
@router.api_route("/tenants/subscriptions/{tenant_id}/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_subscription_endpoints(request: Request, tenant_id: str = Path(...), path: str = ""):
"""Proxy subscription requests directly to tenant service"""
target_path = f"/api/v1/subscriptions/{tenant_id}/{path}".rstrip("/")
target_path = f"/api/v1/tenants/subscriptions/{tenant_id}/{path}".rstrip("/")
return await _proxy_to_tenant_service(request, target_path)
@router.api_route("/subscriptions/plans", methods=["GET", "OPTIONS"])

View File

@@ -300,6 +300,16 @@ async def proxy_tenant_recipes_with_path(request: Request, tenant_id: str = Path
target_path = f"/api/v1/tenants/{tenant_id}/recipes/{path}".rstrip("/")
return await _proxy_to_recipes_service(request, target_path, tenant_id=tenant_id)
# ================================================================
# TENANT-SCOPED POS SERVICE ENDPOINTS
# ================================================================
@router.api_route("/{tenant_id}/pos/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
async def proxy_tenant_pos(request: Request, tenant_id: str = Path(...), path: str = ""):
"""Proxy tenant POS requests to POS service"""
target_path = f"/api/v1/tenants/{tenant_id}/pos/{path}".rstrip("/")
return await _proxy_to_pos_service(request, target_path, tenant_id=tenant_id)
# ================================================================
# PROXY HELPER FUNCTIONS
# ================================================================
@@ -348,6 +358,10 @@ async def _proxy_to_recipes_service(request: Request, target_path: str, tenant_i
"""Proxy request to recipes service"""
return await _proxy_request(request, target_path, settings.RECIPES_SERVICE_URL, tenant_id=tenant_id)
async def _proxy_to_pos_service(request: Request, target_path: str, tenant_id: str = None):
"""Proxy request to POS service"""
return await _proxy_request(request, target_path, settings.POS_SERVICE_URL, tenant_id=tenant_id)
async def _proxy_request(request: Request, target_path: str, service_url: str, tenant_id: str = None):
"""Generic proxy function with enhanced error handling"""