-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_chirps.go
206 lines (167 loc) · 4.93 KB
/
handler_chirps.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strings"
"github.com/giapoldo/chirpy/internal/auth"
"github.com/giapoldo/chirpy/internal/database"
"github.com/google/uuid"
)
var badWords []string = []string{"kerfuffle", "sharbert", "fornax"}
func filterBadWords(chirp string) (cleanChirp string) {
split_chirp := strings.Split(chirp, " ")
for i, word := range split_chirp {
for _, bword := range badWords {
if strings.ToLower(word) == strings.ToLower(bword) {
split_chirp[i] = "****"
}
}
}
cleanChirp = strings.Join(split_chirp, " ")
return
}
// POST /api/chirps
func (cfg *apiConfig) handlerAddChirps(w http.ResponseWriter, r *http.Request) {
decoder := json.NewDecoder(r.Body)
params := parameters{}
err := decoder.Decode(¶ms)
if err != nil {
// an error will be thrown if the JSON is invalid or has the wrong types
// any missing fields will simply have their values in the struct set to their zero value
log.Printf("Error decoding parameters: %s\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
token, err := auth.GetBearerToken(r.Header)
if err != nil {
log.Println("No token in request 1", err)
respondWithError(w, http.StatusUnauthorized, "No token in request 1")
return
}
JWTuserID, err := auth.ValidateJWT(token, cfg.jwtSecret)
if err != nil {
log.Println("No token in request 2", err)
respondWithError(w, http.StatusUnauthorized, "No token in request 2")
return
}
if l := len(params.Body); l > 140 {
respondWithError(w, http.StatusBadRequest, fmt.Sprintf("Chirp longer than 140 characters (%v)", l))
return
}
cleanedBody := filterBadWords(params.Body)
chirp, err := cfg.db.CreateChirp(r.Context(), database.CreateChirpParams{
Body: cleanedBody,
UserID: JWTuserID,
})
if err != nil {
log.Printf("Error creating chirp: %s\n", err)
return
}
new_chirp := chirpData{
ID: chirp.ID.String(),
CreatedAt: chirp.CreatedAt.String(),
UpdatedAt: chirp.UpdatedAt.String(),
Body: chirp.Body,
UserID: chirp.UserID.String(),
}
respondWithJSON(w, http.StatusCreated, new_chirp)
return
}
func (cfg *apiConfig) handlerGetChirps(w http.ResponseWriter, r *http.Request) {
sort := r.URL.Query().Get("sort")
if sort == "" {
sort = "asc"
}
log.Println(sort)
var user_ID uuid.UUID
author_id := r.URL.Query().Get("author_id")
user_ID, err := uuid.Parse(author_id)
if err != nil {
user_ID = uuid.UUID{}
}
log.Println()
log.Println(user_ID)
log.Println()
var db_chirps []database.Chirp
if (user_ID == uuid.UUID{}) {
if sort == "asc" {
db_chirps, err = cfg.db.GetChirps(r.Context())
} else {
db_chirps, err = cfg.db.GetChirpsDESC(r.Context())
}
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't retrieve Chirps")
return
}
} else {
if sort == "asc" {
db_chirps, err = cfg.db.GetChirpsFromUser(r.Context(), user_ID)
} else {
db_chirps, err = cfg.db.GetChirpsFromUserDESC(r.Context(), user_ID)
}
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't retrieve Chirps")
return
}
}
log.Println()
log.Println(db_chirps)
log.Println()
retrieved_chirps := []chirpData{}
for _, chirp := range db_chirps {
retrieved_chirps = append(retrieved_chirps, chirpData{
ID: chirp.ID.String(),
CreatedAt: chirp.CreatedAt.String(),
UpdatedAt: chirp.UpdatedAt.String(),
Body: chirp.Body,
UserID: chirp.UserID.String(),
})
}
respondWithJSON(w, http.StatusOK, retrieved_chirps)
return
}
func (cfg *apiConfig) handlerGetSingletonChirp(w http.ResponseWriter, r *http.Request) {
chirpID := uuid.MustParse(r.PathValue("chirpID"))
chirp, err := cfg.db.GetSingleChirp(r.Context(), chirpID)
if err != nil {
respondWithError(w, http.StatusNotFound, "Couldn't find Chirp")
}
retrieved_chirp := chirpData{
ID: chirp.ID.String(),
CreatedAt: chirp.CreatedAt.String(),
UpdatedAt: chirp.UpdatedAt.String(),
Body: chirp.Body,
UserID: chirp.UserID.String(),
}
respondWithJSON(w, http.StatusOK, retrieved_chirp)
return
}
func (cfg *apiConfig) handlerDeleteSingletonChirp(w http.ResponseWriter, r *http.Request) {
chirpID := uuid.MustParse(r.PathValue("chirpID"))
accessToken, err := auth.GetBearerToken(r.Header)
if err != nil {
log.Println("UpdateUser, accestoken:", err)
respondWithError(w, http.StatusUnauthorized, "No token in request")
return
}
jwt_user, err := auth.ValidateJWT(accessToken, cfg.jwtSecret)
if err != nil {
log.Println("UpdateUser, validatejwt:", err)
respondWithError(w, http.StatusUnauthorized, "Malformed token")
return
}
chirp, err := cfg.db.GetSingleChirp(r.Context(), chirpID)
if err != nil {
respondWithError(w, http.StatusNotFound, "Couldn't find Chirp")
return
}
if jwt_user != chirp.UserID {
respondWithError(w, http.StatusForbidden, "User mismatch")
return
}
cfg.db.DeleteSingletonChirps(r.Context(), chirp.ID)
respondWithJSON(w, http.StatusNoContent, "")
return
}