-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_chirps_create.go
73 lines (59 loc) · 1.62 KB
/
handler_chirps_create.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
package main
import (
"encoding/json"
"net/http"
"strconv"
"github.com/jcsmurph/chirpy/internal/auth"
)
type Chirp struct {
ID int `json:"id"`
Body string `json:"body"`
AuthorID int `json:"author_id"`
}
func (cfg *apiConfig) handlerChirpsCreate(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Body string `json:"body"`
}
token, err := auth.GetBearerToken(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't find JWT")
return
}
validAccessToken := auth.ValidateAccessToken(token, cfg.jwtSecret)
if validAccessToken != nil {
respondWithError(w, http.StatusUnauthorized, "Token is not an access token")
return
}
subject, err := auth.ValidateJWT(token, cfg.jwtSecret)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't validate JWT")
return
}
idInt, err := strconv.Atoi(subject)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Unable to convert ID from string to integer")
return
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
decodeErr := decoder.Decode(¶ms)
if decodeErr != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters")
return
}
cleaned, err := validateChirp(params.Body)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
chirp, err := cfg.DB.CreateChirp(cleaned, idInt)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't create chirp")
return
}
respondWithJSON(w, http.StatusCreated, Chirp{
ID: chirp.ID,
Body: chirp.Body,
AuthorID: chirp.AuthorID,
})
}