-
Notifications
You must be signed in to change notification settings - Fork 1
/
wishlist_service.go
223 lines (192 loc) · 6.53 KB
/
wishlist_service.go
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package services
import (
"encoding/json"
"log"
"net/http"
"strconv"
"github.com/gklps/mittai-backend/db"
"github.com/gklps/mittai-backend/models"
"github.com/gorilla/mux"
)
type WishlistService struct {
DB *db.Repository
}
func NewWishlistService(db *db.Repository) *WishlistService {
return &WishlistService{
DB: db,
}
}
func (ws *WishlistService) RegisterRoutes(r *mux.Router) {
r.HandleFunc("/wishlist/{user_id}", ws.GetWishlistItemsByUserID).Methods(http.MethodGet)
r.HandleFunc("/wishlist/check/{user_id}/{product_id}", ws.CheckItemInWishlist).Methods(http.MethodGet)
r.HandleFunc("/wishlist", ws.AddToWishlist).Methods(http.MethodPost)
r.HandleFunc("/wishlist/{user_id}/{product_id}", ws.RemoveFromWishlist).Methods(http.MethodDelete)
}
// @Summary Add an item to the wishlist
// @Tags Wishlist
// @Accept json
// @Produce json
// @Param item body models.WishlistRequest true "Wishlist item"
// @Success 200 {object} map[string]int "Item added successfully"
// @Failure 400 "Bad request"
// @Failure 500 "Failed to add item to wishlist"
// @Router /wishlist [post]
func (ws *WishlistService) AddToWishlist(w http.ResponseWriter, r *http.Request) {
var item models.Wishlist
err := json.NewDecoder(r.Body).Decode(&item)
if err != nil {
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
insertedID, err := ws.storeItemInWishlist(item)
if err != nil {
log.Println(err)
http.Error(w, "Failed to add item to wishlist", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]int{"wishlist_id": insertedID})
}
func (ws *WishlistService) storeItemInWishlist(item models.Wishlist) (int, error) {
// First, check if the product already exists in the wishlist for the user
queryCheck := `SELECT COUNT(*) FROM wishlist WHERE user_id = ? AND product_id = ?`
var count int
err := ws.DB.QueryRow(queryCheck, item.UserID, item.ProductID).Scan(&count)
if err != nil {
return 0, err
}
if count > 0 {
log.Println("The product is already in the wishlist for the user")
return 0, nil
}
// Proceed with the insert if it doesn't exist
query := `INSERT INTO wishlist (user_id, product_id, created_at, updated_at) VALUES (?, ?, ?, ?)`
result, err := ws.DB.Exec(query, item.UserID, item.ProductID, item.CreatedAt, item.UpdatedAt)
if err != nil {
return 0, err
}
lastInsertedID, err := result.LastInsertId()
return int(lastInsertedID), err
}
// @Summary Remove an item from the wishlist
// @Tags Wishlist
// @Produce json
// @Param user_id path int true "User ID"
// @Param product_id path int true "Product ID"
// @Success 200 {string} string "Item removed successfully"
// @Failure 400 "Bad request"
// @Failure 500 "Failed to remove item from wishlist"
// @Router /wishlist/{user_id}/{product_id} [delete]
func (ws *WishlistService) RemoveFromWishlist(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userIDStr := vars["user_id"]
productIDStr := vars["product_id"]
userID, err := strconv.Atoi(userIDStr)
if err != nil {
http.Error(w, "Invalid user ID", http.StatusBadRequest)
return
}
productID, err := strconv.Atoi(productIDStr)
if err != nil {
http.Error(w, "Invalid product ID", http.StatusBadRequest)
return
}
err = ws.removeItemFromWishlist(userID, productID)
if err != nil {
log.Println(err)
http.Error(w, "Failed to remove item from wishlist", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Item removed successfully"))
}
func (ws *WishlistService) removeItemFromWishlist(userID int, productID int) error {
query := `DELETE FROM wishlist WHERE user_id = ? AND product_id = ?`
_, err := ws.DB.Exec(query, userID, productID)
return err
}
// @Summary Get all wishlist items for a user
// @Tags Wishlist
// @Produce json
// @Param user_id path int true "User ID"
// @Success 200 {array} models.Wishlist "Wishlist items retrieved successfully"
// @Failure 400 "Bad request"
// @Failure 500 "Failed to fetch wishlist items"
// @Router /wishlist/{user_id} [get]
func (ws *WishlistService) GetWishlistItemsByUserID(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
log.Println("Inside GetWishlistItemsByUserID")
userIDStr := vars["user_id"]
userID, err := strconv.Atoi(userIDStr)
if err != nil {
http.Error(w, "Invalid user ID", http.StatusBadRequest)
return
}
wishlistItems, err := ws.fetchWishlistItemsByUserID(userID)
if err != nil {
log.Println(err)
http.Error(w, "Failed to fetch wishlist items", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(wishlistItems)
}
func (ws *WishlistService) fetchWishlistItemsByUserID(userID int) ([]*models.Wishlist, error) {
query := `SELECT id, user_id, product_id, created_at, updated_at FROM wishlist WHERE user_id = ?`
rows, err := ws.DB.Query(query, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var items []*models.Wishlist
for rows.Next() {
var item models.Wishlist
err := rows.Scan(&item.ID, &item.UserID, &item.ProductID, &item.CreatedAt, &item.UpdatedAt)
if err != nil {
return nil, err
}
items = append(items, &item)
}
return items, nil
}
// @Summary Check if an item exists in the wishlist
// @Tags Wishlist
// @Produce json
// @Param user_id path int true "User ID"
// @Param product_id path int true "Product ID"
// @Success 200 {object} map[string]bool "Item exists in the wishlist"
// @Failure 400 "Bad request"
// @Failure 500 "Failed to check item in wishlist"
// @Router /wishlist/check/{user_id}/{product_id} [get]
func (ws *WishlistService) CheckItemInWishlist(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
userIDStr := vars["user_id"]
productIDStr := vars["product_id"]
userID, err := strconv.Atoi(userIDStr)
if err != nil {
http.Error(w, "Invalid user ID", http.StatusBadRequest)
return
}
productID, err := strconv.Atoi(productIDStr)
if err != nil {
http.Error(w, "Invalid product ID", http.StatusBadRequest)
return
}
exists, err := ws.itemExistsInWishlist(userID, productID)
if err != nil {
log.Println(err)
http.Error(w, "Failed to check item in wishlist", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]bool{"exists": exists})
}
func (ws *WishlistService) itemExistsInWishlist(userID int, productID int) (bool, error) {
query := `SELECT COUNT(*) FROM wishlist WHERE user_id = ? AND product_id = ?`
var count int
err := ws.DB.QueryRow(query, userID, productID).Scan(&count)
if err != nil {
return false, err
}
return count > 0, nil
}