Add queue APIs
This commit is contained in:
parent
4e74bbb443
commit
3775191fd1
4 changed files with 382 additions and 0 deletions
167
backend/endpoints/queue.py
Normal file
167
backend/endpoints/queue.py
Normal file
|
@ -0,0 +1,167 @@
|
|||
from fastapi import APIRouter, HTTPException
|
||||
from pymongo import MongoClient
|
||||
from bson import ObjectId
|
||||
from datetime import datetime
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
# Router per le API della queue
|
||||
queue_router = APIRouter(prefix="/queue")
|
||||
|
||||
# Connessione MongoDB
|
||||
client = MongoClient("mongodb://localhost:27017/")
|
||||
db = client["simple_db"]
|
||||
queue_collection = db["queue"]
|
||||
|
||||
# Modelli Pydantic
|
||||
class QueueItem(BaseModel):
|
||||
id: str
|
||||
titolo: str
|
||||
coverUrl: str
|
||||
color: str
|
||||
artista: str
|
||||
voti: int = 0
|
||||
|
||||
class QueueItemCreate(BaseModel):
|
||||
titolo: str
|
||||
coverUrl: str
|
||||
color: str
|
||||
artista: str
|
||||
voti: int = 0
|
||||
|
||||
class QueueItemUpdate(BaseModel):
|
||||
titolo: Optional[str] = None
|
||||
coverUrl: Optional[str] = None
|
||||
color: Optional[str] = None
|
||||
artista: Optional[str] = None
|
||||
|
||||
class VoteUpdate(BaseModel):
|
||||
increment: bool = True # True per incrementare, False per decrementare
|
||||
|
||||
@queue_router.post("/add")
|
||||
async def add_item(item: QueueItemCreate):
|
||||
"""POST: Aggiunge un nuovo item alla queue"""
|
||||
try:
|
||||
# Genera un ID univoco
|
||||
import uuid
|
||||
item_id = str(uuid.uuid4())
|
||||
|
||||
new_item = {
|
||||
"id": item_id,
|
||||
"titolo": item.titolo,
|
||||
"coverUrl": item.coverUrl,
|
||||
"color": item.color,
|
||||
"artista": item.artista,
|
||||
"voti": item.voti,
|
||||
"created_at": datetime.now().isoformat()
|
||||
}
|
||||
|
||||
result = queue_collection.insert_one(new_item)
|
||||
new_item["_id"] = str(result.inserted_id)
|
||||
|
||||
return {"success": True, "message": "Item aggiunto alla queue", "data": new_item}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Errore aggiunta item: {str(e)}")
|
||||
|
||||
@queue_router.get("/read")
|
||||
async def read_queue():
|
||||
"""GET: Legge tutti gli item della queue ordinati per voti"""
|
||||
try:
|
||||
# Trova tutti gli item ordinati per voti (decrescente)
|
||||
items = list(queue_collection.find().sort("voti", -1))
|
||||
|
||||
# Converti ObjectId in stringa
|
||||
for item in items:
|
||||
item["_id"] = str(item["_id"])
|
||||
|
||||
return {"success": True, "data": items, "count": len(items)}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Errore lettura queue: {str(e)}")
|
||||
|
||||
@queue_router.get("/read/{item_id}")
|
||||
async def read_item(item_id: str):
|
||||
"""GET: Legge un singolo item per ID"""
|
||||
try:
|
||||
item = queue_collection.find_one({"id": item_id})
|
||||
if item:
|
||||
item["_id"] = str(item["_id"])
|
||||
return {"success": True, "data": item}
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail="Item non trovato")
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Errore lettura item: {str(e)}")
|
||||
|
||||
@queue_router.delete("/delete/{item_id}")
|
||||
async def delete_item(item_id: str):
|
||||
"""DELETE: Elimina un item dalla queue"""
|
||||
try:
|
||||
result = queue_collection.delete_one({"id": item_id})
|
||||
|
||||
if result.deleted_count > 0:
|
||||
return {"success": True, "message": "Item eliminato dalla queue"}
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail="Item non trovato")
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Errore eliminazione item: {str(e)}")
|
||||
|
||||
@queue_router.put("/edit/{item_id}")
|
||||
async def edit_item(item_id: str, item_update: QueueItemUpdate):
|
||||
"""PUT: Modifica un item nella queue"""
|
||||
try:
|
||||
# Prepara i campi da aggiornare
|
||||
update_data = {}
|
||||
for field, value in item_update.dict(exclude_unset=True).items():
|
||||
if value is not None:
|
||||
update_data[field] = value
|
||||
|
||||
if not update_data:
|
||||
raise HTTPException(status_code=400, detail="Nessun campo da aggiornare")
|
||||
|
||||
update_data["updated_at"] = datetime.now().isoformat()
|
||||
|
||||
result = queue_collection.update_one(
|
||||
{"id": item_id},
|
||||
{"$set": update_data}
|
||||
)
|
||||
|
||||
if result.modified_count > 0:
|
||||
return {"success": True, "message": "Item aggiornato"}
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail="Item non trovato")
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Errore aggiornamento item: {str(e)}")
|
||||
|
||||
@queue_router.patch("/vote/{item_id}")
|
||||
async def update_vote(item_id: str, vote_update: VoteUpdate):
|
||||
"""PATCH: Incrementa/decrementa i voti di un item"""
|
||||
try:
|
||||
increment_value = 1 if vote_update.increment else -1
|
||||
|
||||
result = queue_collection.update_one(
|
||||
{"id": item_id},
|
||||
{"$inc": {"voti": increment_value}}
|
||||
)
|
||||
|
||||
if result.modified_count > 0:
|
||||
# Recupera l'item aggiornato
|
||||
updated_item = queue_collection.find_one({"id": item_id})
|
||||
updated_item["_id"] = str(updated_item["_id"])
|
||||
|
||||
action = "incrementato" if vote_update.increment else "decrementato"
|
||||
return {
|
||||
"success": True,
|
||||
"message": f"Voti {action} con successo",
|
||||
"data": updated_item
|
||||
}
|
||||
else:
|
||||
raise HTTPException(status_code=404, detail="Item non trovato")
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=500, detail=f"Errore aggiornamento voti: {str(e)}")
|
|
@ -3,6 +3,7 @@ from fastapi import FastAPI
|
|||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from endpoints.geo_access import geo_access_router
|
||||
from endpoints.queue import queue_router
|
||||
from routes import router
|
||||
|
||||
load_dotenv()
|
||||
|
@ -21,6 +22,7 @@ app.add_middleware(
|
|||
# Includi le route
|
||||
app.include_router(router)
|
||||
app.include_router(geo_access_router)
|
||||
app.include_router(queue_router)
|
||||
|
||||
|
||||
@app.post("/auth")
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue