fix: recursive call in get_events route

- Separated route handler from database function
- Fixed infinite recursion
- Improved error handling
This commit is contained in:
Josh Finlay 2025-01-08 09:18:05 +10:00
parent acf51a9242
commit db6430e115
1 changed files with 31 additions and 25 deletions

View File

@ -197,30 +197,36 @@ async def get_settings():
return settings return settings
async def get_events(limit: int = 10, offset: int = 0): async def get_events(limit: int = 10, offset: int = 0):
"""Get recent gate events with pagination""" """Get events from database with pagination"""
async with get_db() as db: try:
db.row_factory = aiosqlite.Row async with aiosqlite.connect(DB_PATH) as db:
# Get total count
async with db.execute("SELECT COUNT(*) FROM events") as cursor:
total = (await cursor.fetchone())[0]
# Get total count # Get paginated events
cursor = await db.execute("SELECT COUNT(*) as count FROM events") async with db.execute(
row = await cursor.fetchone() "SELECT timestamp, action, source, success FROM events ORDER BY timestamp DESC LIMIT ? OFFSET ?",
total_count = row['count'] (limit, offset)
) as cursor:
events = [
{
"timestamp": row[0],
"action": row[1],
"source": row[2],
"success": bool(row[3])
}
for row in await cursor.fetchall()
]
# Get paginated events return {
cursor = await db.execute( "events": events,
""" "total": total,
SELECT * FROM events "hasMore": total > (offset + limit)
ORDER BY timestamp DESC }
LIMIT ? OFFSET ? except Exception as e:
""", logger.error(f"Failed to get events: {e}", exc_info=True)
(limit, offset) raise HTTPException(status_code=500, detail="Failed to get events")
)
events = await cursor.fetchall()
return {
"events": [dict(event) for event in events],
"total": total_count,
"hasMore": (offset + limit) < total_count
}
# Set up MQTT event logging # Set up MQTT event logging
async def log_mqtt_event(action: str, success: bool = True): async def log_mqtt_event(action: str, success: bool = True):
@ -441,7 +447,7 @@ async def get_status():
raise HTTPException(status_code=500, detail="Failed to get gate status") raise HTTPException(status_code=500, detail="Failed to get gate status")
@app.get("/api/events") @app.get("/api/events")
async def get_events(limit: int = 10, offset: int = 0): async def get_events_route(limit: int = 10, offset: int = 0):
"""Get recent gate events with pagination""" """Get recent gate events with pagination"""
return await get_events(limit, offset) return await get_events(limit, offset)