|
4 | 4 | from app.schemas.images import ErrorResponse |
5 | 5 | from app.utils.images import image_util_parse_metadata |
6 | 6 | from pydantic import BaseModel |
7 | | -from app.database.images import db_toggle_image_favourite_status |
| 7 | +from app.database.images import db_toggle_image_favourite_status, db_get_image_by_id |
8 | 8 | from app.logging.setup_logging import get_logger |
9 | 9 |
|
| 10 | + |
10 | 11 | # Initialize logger |
11 | 12 | logger = get_logger(__name__) |
12 | 13 | router = APIRouter() |
@@ -97,26 +98,37 @@ class ToggleFavouriteRequest(BaseModel): |
97 | 98 |
|
98 | 99 | @router.post("/toggle-favourite") |
99 | 100 | def toggle_favourite(req: ToggleFavouriteRequest): |
| 101 | + """ |
| 102 | + Toggle the favorite status of an image. |
| 103 | + """ |
100 | 104 | image_id = req.image_id |
101 | 105 | try: |
102 | 106 | success = db_toggle_image_favourite_status(image_id) |
103 | 107 | if not success: |
104 | 108 | raise HTTPException( |
105 | | - status_code=404, detail="Image not found or failed to toggle" |
| 109 | + status_code=status.HTTP_404_NOT_FOUND, |
| 110 | + detail="Image not found or failed to toggle", |
106 | 111 | ) |
107 | 112 | # Fetch updated status to return |
108 | | - image = next( |
109 | | - (img for img in db_get_all_images() if img["id"] == image_id), None |
110 | | - ) |
| 113 | + image = db_get_image_by_id(image_id) |
| 114 | + if not image: |
| 115 | + raise HTTPException( |
| 116 | + status_code=status.HTTP_404_NOT_FOUND, |
| 117 | + detail="Image not found after toggle", |
| 118 | + ) |
111 | 119 | return { |
112 | 120 | "success": True, |
113 | 121 | "image_id": image_id, |
114 | 122 | "isFavourite": image.get("isFavourite", False), |
115 | 123 | } |
116 | | - |
| 124 | + except HTTPException: |
| 125 | + raise # Re-raise HTTPExceptions to preserve status codes |
117 | 126 | except Exception as e: |
118 | 127 | logger.error(f"error in /toggle-favourite route: {e}") |
119 | | - raise HTTPException(status_code=500, detail=f"Internal server error: {e}") |
| 128 | + raise HTTPException( |
| 129 | + status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, |
| 130 | + detail=f"Internal server error: {e}", |
| 131 | + ) |
120 | 132 |
|
121 | 133 |
|
122 | 134 | class ImageInfoResponse(BaseModel): |
|
0 commit comments