-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler_chirps_create.go
More file actions
114 lines (82 loc) · 2.22 KB
/
handler_chirps_create.go
File metadata and controls
114 lines (82 loc) · 2.22 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
package main
import (
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"github.com/SandeshNarayan/chirpy/internal/auth"
"github.com/SandeshNarayan/chirpy/internal/database"
"github.com/google/uuid"
)
type Chirp struct{
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
UserID uuid.UUID `json:"user_id"`
Body string `json:"body"`
}
func (cfg *apiConfig) handlerChirpsCreate(w http.ResponseWriter, r *http.Request){
tokenString, err := auth.GetBearerToken(r.Header)
if err!=nil{
respondWithError(w, http.StatusUnauthorized, "Missing or invalid token", err)
return
}
userID, err:= auth.ValidateJWT(tokenString, cfg.jwtSecret)
if err!=nil {
respondWithError(w, http.StatusUnauthorized, "Invalid token", err)
return
}
type parameters struct{
Body string `json:"body"`
}
params:=parameters{}
if err:= json.NewDecoder(r.Body).Decode(¶ms); err!= nil{
respondWithError(w, http.StatusBadRequest, "Invalid JSON body", err)
return
}
cleaned, err:= validatChirp(params.Body)
if err!= nil{
respondWithError(w, http.StatusBadRequest, "Invalid chirp body", err)
return
}
chirp, err := cfg.dbQueries.CreateChirp(r.Context(), database.CreateChirpParams{
Body: cleaned,
UserID: userID,
})
if err!=nil{
respondWithError(w, http.StatusInternalServerError, "Couldnt create chirp", err)
return
}
respondWithJson(w, http.StatusCreated, Chirp{
ID: chirp.ID,
CreatedAt: chirp.CreatedAt,
UpdatedAt: chirp.UpdatedAt,
UserID: userID,
Body: cleaned,
})
}
func validatChirp(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] = "****"
}
}
new_body := strings.Join(words, " ")
return new_body
}