-
Notifications
You must be signed in to change notification settings - Fork 0
/
togglecommentlikes.go
116 lines (94 loc) · 2.69 KB
/
togglecommentlikes.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
package main
import (
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
auth "github.com/jaydee029/Verses/internal/auth"
"github.com/jaydee029/Verses/internal/database"
)
type toggCommentLike struct {
Liked bool `json:"liked"`
Likes_count int `json:"likes_count"`
}
func (cfg *apiconfig) toggCommentLike(w http.ResponseWriter, r *http.Request) {
token, err := auth.BearerHeader(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, err.Error())
return
}
user_id, err := auth.ValidateToken(token, cfg.jwtsecret)
if err != nil {
respondWithError(w, http.StatusUnauthorized, err.Error())
return
}
commentidstr := chi.URLParam(r, "commentid")
Commentid, err := strconv.Atoi(commentidstr)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
}
var pgUUID pgtype.UUID
err = pgUUID.Scan(user_id)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
tx, err := cfg.DBpool.Begin(r.Context())
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
qtx := cfg.DB.WithTx(tx)
defer func() {
if tx != nil {
tx.Rollback(r.Context())
}
}()
If_liked, err := qtx.IfCommentLiked(r.Context(), database.IfCommentLikedParams{
CommentID: int32(Commentid),
UserID: pgUUID,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
var liked bool
var likes int32
if If_liked {
err = qtx.RemoveCommentLike(r.Context(), database.RemoveCommentLikeParams{
CommentID: int32(Commentid),
UserID: pgUUID,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, "error while disliking the comment")
return
}
likes, err = qtx.DecreaseCommentLikeCount(r.Context(), int32(Commentid))
if err != nil {
respondWithError(w, http.StatusInternalServerError, "error while decreasing the like count")
return
}
liked = false
} else {
err = qtx.AddCommentLike(r.Context(), database.AddCommentLikeParams{
CommentID: int32(Commentid),
UserID: pgUUID,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, "error while liking the comment")
return
}
likes, err = qtx.IncreaseCommentLikeCount(r.Context(), int32(Commentid))
if err != nil {
respondWithError(w, http.StatusInternalServerError, "error while increasing the like count")
return
}
liked = true
}
tx.Commit(r.Context())
tx = nil
respondWithJson(w, http.StatusAccepted, toggCommentLike{
Liked: liked,
Likes_count: int(likes),
})
}