From 9cae9c1d2a0b4f7fa72f3075541b9ffafe1a7275 Mon Sep 17 00:00:00 2001 From: Zach Berwaldt Date: Fri, 15 Mar 2024 18:49:43 -0400 Subject: Add routes for preference, clean up and add types --- api/internal/controllers/user.go | 59 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 55 insertions(+), 4 deletions(-) (limited to 'api/internal/controllers/user.go') diff --git a/api/internal/controllers/user.go b/api/internal/controllers/user.go index 76dedc8..dbb09cf 100644 --- a/api/internal/controllers/user.go +++ b/api/internal/controllers/user.go @@ -1,17 +1,68 @@ package controllers import ( - "github.com/gin-gonic/gin" + "database/sql" + "errors" + "log" "net/http" + "water/api/internal/database" + "water/api/internal/models" + + "github.com/gin-gonic/gin" ) func GetUser(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"message": "User found"}) } func GetUserPreferences(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"message": "Preferences fetched successfully"}) + db := database.EstablishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(db) + + var preference models.Preference + + row := db.QueryRow("SELECT id, user_id, color, size_id FROM Preferences WHERE user_id = ?", c.Param("id")) + if err := row.Scan(&preference.ID, &preference.UserID, &preference.Color, &preference.SizeID); err != nil { + if errors.Is(err, sql.ErrNoRows) { + c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) + return + } else { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + } + + c.JSON(http.StatusOK, preference) } func UpdateUserPreferences(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{"message": "Preferences updated successfully"}) -} \ No newline at end of file + db := database.EstablishDBConnection() + defer func(db *sql.DB) { + err := db.Close() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + }(db) + + var newPreferences models.Preference + if err := c.BindJSON(&newPreferences); err != nil { + c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()}) + return + } + + log.Printf("newPreferences: %v", newPreferences) + + _, err := db.Exec("UPDATE Preferences SET color = ?, size_id = ? WHERE id = ?", newPreferences.Color, newPreferences.SizeID, newPreferences.ID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + c.Status(http.StatusNoContent) +} -- cgit v1.1