-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler_chirps.go
More file actions
178 lines (156 loc) · 4.73 KB
/
handler_chirps.go
File metadata and controls
178 lines (156 loc) · 4.73 KB
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
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/acramatte/Chirpy/internal/auth"
"github.com/acramatte/Chirpy/internal/database"
"github.com/google/uuid"
"net/http"
"strings"
"time"
)
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) handlerChirpGet(w http.ResponseWriter, r *http.Request) {
userID, err := uuid.Parse(r.PathValue("chirpID"))
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid chirp ID", err)
return
}
dbChirp, err := cfg.db.GetChirp(r.Context(), userID)
if err != nil {
respondWithError(w, http.StatusNotFound, "Chirp not found", 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) handlerChirpDelete(w http.ResponseWriter, r *http.Request) {
token, err := auth.GetBearerToken(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't find JWT", err)
return
}
userID, err := auth.ValidateJWT(token, cfg.jwtSecret)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't validate JWT", err)
return
}
chirpID, err := uuid.Parse(r.PathValue("chirpID"))
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid chirp ID", err)
return
}
chirp, err := cfg.db.GetChirp(r.Context(), chirpID)
if err != nil {
respondWithError(w, http.StatusNotFound, "Chirp not found", err)
return
}
if chirp.UserID != userID {
respondWithError(w, http.StatusForbidden, "Not your chirp", err)
return
}
err = cfg.db.DeleteChirp(r.Context(), chirpID)
if err != nil {
respondWithError(w, http.StatusInternalServerError, fmt.Sprintf("Couldn't delete chirp %v", chirpID), err)
return
}
respondWithJSON(w, http.StatusNoContent, struct{}{})
}
func (cfg *apiConfig) handlerChirpsRetrieve(w http.ResponseWriter, r *http.Request) {
sort := r.URL.Query().Get("sort")
order := strings.ToLower(sort)
if order != "asc" && order != "desc" {
order = "asc" // Default to ASC if invalid
}
s := r.URL.Query().Get("author_id")
dbChirps, err := cfg.getChirps(r.Context(), s, order)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't retrieve chirps", err)
return
}
var chirps []Chirp
for _, dbChirp := range dbChirps {
chirps = append(chirps, Chirp{
ID: dbChirp.ID,
CreatedAt: dbChirp.CreatedAt,
UpdatedAt: dbChirp.UpdatedAt,
Body: dbChirp.Body,
UserID: dbChirp.UserID,
})
}
respondWithJSON(w, http.StatusOK, chirps)
}
func (cfg *apiConfig) getChirps(c context.Context, authorId, sortOrder string) ([]database.Chirp, error) {
if authorId == "" {
return cfg.db.GetChirps(c, sortOrder)
}
parsedID, err := uuid.Parse(authorId)
if err != nil {
return nil, fmt.Errorf("Couldn't parse user id: %w", err)
}
return cfg.db.GetChirpsByAuthorId(c, database.GetChirpsByAuthorIdParams{
UserID: parsedID,
Column2: sortOrder,
})
}
func (cfg *apiConfig) handlerChirpsCreate(w http.ResponseWriter, r *http.Request) {
token, err := auth.GetBearerToken(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Unauthorized", err)
return
}
userID, err := auth.ValidateJWT(token, cfg.jwtSecret)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Unauthorized", err)
return
}
type parameters struct {
Body string `json:"body"`
}
decoder := json.NewDecoder(r.Body)
defer r.Body.Close()
params := parameters{}
err = decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters", err)
return
}
if len(params.Body) > 140 {
respondWithError(w, http.StatusBadRequest, "Chirp is too long", nil)
return
}
filteredBody := getCleanedBody(params.Body)
chirp, err := cfg.db.CreateChirp(r.Context(), database.CreateChirpParams{
Body: filteredBody,
UserID: userID,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't create chirp", err)
}
respondWithJSON(w, http.StatusCreated, Chirp{ID: chirp.ID, CreatedAt: chirp.CreatedAt, UpdatedAt: chirp.UpdatedAt, Body: chirp.Body, UserID: chirp.UserID})
}
func getCleanedBody(body string) string {
words := strings.Split(body, " ")
var filtered []string
for _, word := range words {
lowerCase := strings.ToLower(word)
if strings.Contains(lowerCase, "kerfuffle") || strings.Contains(lowerCase, "sharbert") || strings.Contains(lowerCase, "fornax") {
filtered = append(filtered, "****")
} else {
filtered = append(filtered, word)
}
}
return strings.Join(filtered, " ")
}