diff options
Diffstat (limited to 'api/internal/controllers/user.go')
-rw-r--r-- | api/internal/controllers/user.go | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/api/internal/controllers/user.go b/api/internal/controllers/user.go new file mode 100644 index 0000000..dbb09cf --- /dev/null +++ b/api/internal/controllers/user.go | |||
@@ -0,0 +1,68 @@ | |||
1 | package controllers | ||
2 | |||
3 | import ( | ||
4 | "database/sql" | ||
5 | "errors" | ||
6 | "log" | ||
7 | "net/http" | ||
8 | "water/api/internal/database" | ||
9 | "water/api/internal/models" | ||
10 | |||
11 | "github.com/gin-gonic/gin" | ||
12 | ) | ||
13 | |||
14 | func GetUser(c *gin.Context) { | ||
15 | c.JSON(http.StatusOK, gin.H{"message": "User found"}) | ||
16 | } | ||
17 | func GetUserPreferences(c *gin.Context) { | ||
18 | db := database.EstablishDBConnection() | ||
19 | defer func(db *sql.DB) { | ||
20 | err := db.Close() | ||
21 | if err != nil { | ||
22 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
23 | return | ||
24 | } | ||
25 | }(db) | ||
26 | |||
27 | var preference models.Preference | ||
28 | |||
29 | row := db.QueryRow("SELECT id, user_id, color, size_id FROM Preferences WHERE user_id = ?", c.Param("id")) | ||
30 | if err := row.Scan(&preference.ID, &preference.UserID, &preference.Color, &preference.SizeID); err != nil { | ||
31 | if errors.Is(err, sql.ErrNoRows) { | ||
32 | c.JSON(http.StatusNotFound, gin.H{"error": err.Error()}) | ||
33 | return | ||
34 | } else { | ||
35 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
36 | return | ||
37 | } | ||
38 | } | ||
39 | |||
40 | c.JSON(http.StatusOK, preference) | ||
41 | } | ||
42 | |||
43 | func UpdateUserPreferences(c *gin.Context) { | ||
44 | db := database.EstablishDBConnection() | ||
45 | defer func(db *sql.DB) { | ||
46 | err := db.Close() | ||
47 | if err != nil { | ||
48 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
49 | return | ||
50 | } | ||
51 | }(db) | ||
52 | |||
53 | var newPreferences models.Preference | ||
54 | if err := c.BindJSON(&newPreferences); err != nil { | ||
55 | c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()}) | ||
56 | return | ||
57 | } | ||
58 | |||
59 | log.Printf("newPreferences: %v", newPreferences) | ||
60 | |||
61 | _, err := db.Exec("UPDATE Preferences SET color = ?, size_id = ? WHERE id = ?", newPreferences.Color, newPreferences.SizeID, newPreferences.ID) | ||
62 | if err != nil { | ||
63 | c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) | ||
64 | return | ||
65 | } | ||
66 | |||
67 | c.Status(http.StatusNoContent) | ||
68 | } | ||