-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_posts.go
187 lines (158 loc) · 4.62 KB
/
api_posts.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
package main
import (
"errors"
"net/http"
"sort"
"strings"
"time"
"github.com/google/uuid"
"github.com/thewerther/webserver/internal/database"
)
type ChirpRequest struct {
Body string `json:"body"`
}
type ChirpResponse struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Email string `json:"email"`
UserID uuid.UUID `json:"user_id"`
Body string `json:"body"`
}
func (cfg *ApiConfig) createChirp(w http.ResponseWriter, req *http.Request) {
chirpReq := ChirpRequest{}
err := decodeRequestBody(&chirpReq, req)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Error Decoding request", err)
return
}
userExists, err := authenticate(req, cfg)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Invalid token", err)
return
}
if len(chirpReq.Body) > 140 {
respondWithError(w, http.StatusBadRequest, "", errors.New("Chirp is too long!"))
return
}
newChirp, err := cfg.Database.CreateChirp(
req.Context(),
database.CreateChirpParams{
Body: cleanBody(chirpReq.Body),
UserID: userExists.ID,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Error creating Chirp in database", err)
return
}
response := ChirpResponse{
ID: newChirp.ID,
CreatedAt: newChirp.CreatedAt,
UpdatedAt: newChirp.UpdatedAt,
Email: userExists.Email,
UserID: userExists.ID,
Body: newChirp.Body,
}
respondWithJSON(w, http.StatusCreated, response)
}
func cleanBody(body string) string {
profaneWords := map[string]struct{}{
"kerfuffle": {},
"sharbert": {},
"fornax": {},
"Kerfuffle": {},
"Sharbert": {},
"Fornax": {},
}
msgWords := strings.Split(body, " ")
for idx, word := range msgWords {
if _, exists := profaneWords[word]; exists {
msgWords[idx] = strings.ReplaceAll(msgWords[idx], word, strings.Repeat("*", 4))
}
}
return strings.Join(msgWords, " ")
}
func (cfg *ApiConfig) getChirps(w http.ResponseWriter, req *http.Request) {
dbChirps, err := cfg.Database.GetChirps(req.Context())
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Error querying chirps by user id from database", err)
return
}
authorID := uuid.Nil
authorIDParam := req.URL.Query().Get("author_id")
if authorIDParam != "" {
authorID, err = uuid.Parse(authorIDParam)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Error parsing user id fro mrequest", err)
return
}
}
// default is "asc"
sortDir := "asc"
sortParam := req.URL.Query().Get("sort")
if sortParam == "desc" {
sortDir = "desc"
}
sortedChirps := []ChirpResponse{}
for _, chirp := range dbChirps {
if authorID != uuid.Nil && chirp.UserID != authorID {
continue
}
sortedChirps = append(sortedChirps, ChirpResponse{
ID: chirp.ID,
CreatedAt: chirp.CreatedAt,
UpdatedAt: chirp.UpdatedAt,
UserID: chirp.UserID,
Body: chirp.Body,
})
}
sort.Slice(sortedChirps, func(i, j int) bool {
if sortDir == "desc" {
return sortedChirps[i].CreatedAt.After(sortedChirps[j].CreatedAt)
}
return sortedChirps[i].CreatedAt.Before(sortedChirps[j].CreatedAt)
})
respondWithJSON(w, http.StatusOK, sortedChirps)
}
func (cfg *ApiConfig) getChirpByID(w http.ResponseWriter, req *http.Request) {
chirpID := req.PathValue("chirpID")
id, err := uuid.Parse(chirpID)
if err != nil {
respondWithError(w, http.StatusNotFound, "Error getting chirp id from request", err)
return
}
chirp, err := cfg.Database.GetChirpByID(req.Context(), id)
if err != nil {
respondWithError(w, http.StatusNotFound, "Error querying chirp by id", err)
return
}
respondWithJSON(w, http.StatusOK, chirp)
}
func (cfg *ApiConfig) deleteChirpByID(w http.ResponseWriter, req *http.Request) {
userExists, err := authenticate(req, cfg)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Invalid token", err)
return
}
chirpID := req.PathValue("chirpID")
id, err := uuid.Parse(chirpID)
if err != nil {
respondWithError(w, http.StatusNotFound, "Error getting chirp id from request", err)
return
}
chirpExists, err := cfg.Database.GetChirpByID(req.Context(), id)
if err != nil {
respondWithError(w, http.StatusNotFound, "Error querying chirp by id", err)
return
}
if chirpExists.UserID != userExists.ID {
respondWithError(w, http.StatusForbidden, "Cannot delete another users chirp", err)
return
}
err = cfg.Database.DeleteChirpByID(req.Context(), id)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Error deleting chirp from database", err)
return
}
respondWithJSON(w, http.StatusNoContent, struct{}{})
}