1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
package controllers
import (
"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) {
db, err := database.EstablishDBConnection()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
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) {
db, err := database.EstablishDBConnection()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
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)
}
|