-
Notifications
You must be signed in to change notification settings - Fork 0
/
togglefollow.go
115 lines (97 loc) · 2.67 KB
/
togglefollow.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
package main
import (
"net/http"
"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 togglefollow struct {
Followed bool `json:"followed"`
Followers_count int `json:"followers_count"`
}
func (cfg *apiconfig) toggleFollow(w http.ResponseWriter, r *http.Request) {
username := chi.URLParam(r, "username")
token, err := auth.BearerHeader(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, err.Error())
return
}
follower_id, err := auth.ValidateToken(token, cfg.jwtsecret)
if err != nil {
respondWithError(w, http.StatusUnauthorized, err.Error())
return
}
var pgUUID pgtype.UUID
err = pgUUID.Scan(follower_id)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
followee_id, err := cfg.DB.GetIdfromUsername(r.Context(), username)
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_follow, err := qtx.If_follows(r.Context(), database.If_followsParams{
FollowerID: pgUUID,
FolloweeID: followee_id,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
var followers int32
var followed bool
if if_follow {
err = qtx.Removefollower(r.Context(), database.RemovefollowerParams{
FolloweeID: followee_id,
FollowerID: pgUUID,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
followers, err = qtx.Deletefollower(r.Context(), followee_id)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
followed = false
} else {
err = qtx.Addfollower(r.Context(), database.AddfollowerParams{
FolloweeID: followee_id,
FollowerID: pgUUID,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
followers, err = qtx.Updatefollower(r.Context(), followee_id)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
followed = true
}
tx.Commit(r.Context())
tx = nil
if followed {
go cfg.FollowNotification(followee_id, pgUUID)
}
respondWithJson(w, http.StatusAccepted, togglefollow{
Followers_count: int(followers),
Followed: followed,
})
}