-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_chirp.go
238 lines (207 loc) · 5.93 KB
/
handler_chirp.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package main
import (
"database/sql"
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"github.com/google/uuid"
"github.com/katsuikeda/chirpy/internal/auth"
"github.com/katsuikeda/chirpy/internal/database"
)
type Chirp struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Body string `json:"body"`
UserID uuid.UUID `json:"user_id"`
}
func (cfg *apiConfig) handlerCreateChirp(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Body string `json:"body"`
}
tokenString, err := auth.GetAccessToken(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't find JWT in request header", err)
return
}
userID, err := auth.ValidateJWT(tokenString, cfg.jwtSecret)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't validate JWT", err)
return
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err = decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters", err)
return
}
cleanedBody, err := validateChirp(params.Body)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error(), err)
return
}
chirp, err := cfg.db.CreateChirp(r.Context(), database.CreateChirpParams{
Body: cleanedBody,
UserID: userID,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't create chirp", err)
return
}
respondWithJSON(w, http.StatusCreated, Chirp{
ID: chirp.ID,
CreatedAt: chirp.CreatedAt,
UpdatedAt: chirp.UpdatedAt,
Body: chirp.Body,
UserID: chirp.UserID,
},
)
}
func validateChirp(body string) (string, error) {
const maxChirpLength = 140
if len(body) > maxChirpLength {
return "", errors.New("Chirp is too long")
}
badWords := map[string]struct{}{
"kerfuffle": {},
"sharbert": {},
"fornax": {},
}
cleanedBody := getCleanedBody(body, badWords)
return cleanedBody, nil
}
func getCleanedBody(body string, badWords map[string]struct{}) string {
words := strings.Split(body, " ")
for i, word := range words {
loweredWord := strings.ToLower(word)
if _, ok := badWords[loweredWord]; ok {
words[i] = "****"
}
}
cleaned := strings.Join(words, " ")
return cleaned
}
func (cfg *apiConfig) handlerGetChirps(w http.ResponseWriter, r *http.Request) {
authorIDString := r.URL.Query().Get("author_id")
var dbChirps []database.Chirp
var err error
if authorIDString != "" {
authorID, err := uuid.Parse(authorIDString)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid author ID format", err)
return
}
userExists, err := cfg.db.UserExists(r.Context(), authorID)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't check if user exists", err)
return
}
if !userExists {
respondWithError(w, http.StatusNotFound, "User not found", nil)
return
}
dbChirps, err = cfg.db.GetChirpsByUserID(r.Context(), authorID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
// User exists but has no chirps
respondWithJSON(w, http.StatusOK, []Chirp{})
return
}
respondWithError(w, http.StatusInternalServerError, "Couldn't get chirps", err)
return
}
} else {
dbChirps, err = cfg.db.GetChirps(r.Context())
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't get chirps", err)
return
}
}
IsDescending := false
sortDirectionParam := r.URL.Query().Get("sort")
if sortDirectionParam == "desc" {
IsDescending = true
}
chirps := populateChirps(dbChirps, IsDescending)
respondWithJSON(w, http.StatusOK, chirps)
}
func populateChirps(dbChirps []database.Chirp, IsDescending bool) []Chirp {
chirps := make([]Chirp, len(dbChirps))
if IsDescending {
for i, dbChirp := range dbChirps {
chirps[(len(dbChirps)-1)-i] = Chirp{
ID: dbChirp.ID,
CreatedAt: dbChirp.CreatedAt,
UpdatedAt: dbChirp.UpdatedAt,
Body: dbChirp.Body,
UserID: dbChirp.UserID,
}
}
} else {
for i, dbChirp := range dbChirps {
chirps[i] = Chirp{
ID: dbChirp.ID,
CreatedAt: dbChirp.CreatedAt,
UpdatedAt: dbChirp.UpdatedAt,
Body: dbChirp.Body,
UserID: dbChirp.UserID,
}
}
}
return chirps
}
func (cfg *apiConfig) handlerGetChirpByID(w http.ResponseWriter, r *http.Request) {
chirpIDString := r.PathValue("chirpID")
chirpID, err := uuid.Parse(chirpIDString)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid chirp ID", err)
return
}
dbChirp, err := cfg.db.GetChirpByID(r.Context(), chirpID)
if err != nil {
respondWithError(w, http.StatusNotFound, "Couldn't get chirp by ID", err)
return
}
respondWithJSON(w, http.StatusOK, Chirp{
ID: dbChirp.ID,
CreatedAt: dbChirp.CreatedAt,
UpdatedAt: dbChirp.UpdatedAt,
Body: dbChirp.Body,
UserID: dbChirp.UserID,
})
}
func (cfg *apiConfig) handlerDeleteChirpByID(w http.ResponseWriter, r *http.Request) {
chirpIDString := r.PathValue("chirpID")
chirpID, err := uuid.Parse(chirpIDString)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid chirp ID", err)
return
}
token, err := auth.GetAccessToken(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't find bearer token in request header", err)
return
}
userID, err := auth.ValidateJWT(token, cfg.jwtSecret)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Invalid token", err)
return
}
chirp, err := cfg.db.GetChirpByID(r.Context(), chirpID)
if err != nil {
respondWithError(w, http.StatusNotFound, "Couldn't get chirp by ID", err)
return
}
if chirp.UserID != userID {
respondWithError(w, http.StatusForbidden, "Not authorized to delete this chirp", err)
return
}
if err := cfg.db.DeleteChirpByID(r.Context(), chirp.ID); err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't delete chirp by id", err)
return
}
w.WriteHeader(http.StatusNoContent)
}