-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_polka_send_event.go
63 lines (52 loc) · 1.42 KB
/
handler_polka_send_event.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
package main
import (
"encoding/json"
"errors"
"net/http"
"github.com/ArrayOfLilly/chirpy/internal/auth"
"github.com/ArrayOfLilly/chirpy/internal/database"
)
func (cfg *apiConfig) handlerPolkaSendEvent(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Event string `json:"event"`
Data struct {
UserId int `json:"user_id"`
} `json:"data"`
}
type response struct {}
apiKey, err := auth.GetApiKey(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't find API key")
return
}
if !auth.CheckApiKey(cfg.polkaApiKey, apiKey) {
respondWithError(w, http.StatusUnauthorized, "Unauthorized user")
return
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err = decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters")
return
}
if params.Event != "user.upgraded" {
respondWithError(w, http.StatusNoContent, "")
return
}
user, err := cfg.DB.GetUser(params.Data.UserId)
if err != nil {
if errors.Is(database.ErrNotExist, err) {
respondWithError(w, http.StatusNotFound, "Couldn't find user ID")
return
}
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
err = cfg.DB.UpdateUserIsChirpyRed(user.ID)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
respondWithJSON(w, http.StatusOK, response{})
}