-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_upgrade.go
52 lines (44 loc) · 1.25 KB
/
handler_upgrade.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
package main
import (
"database/sql"
"encoding/json"
"errors"
"net/http"
"github.com/google/uuid"
"github.com/katsuikeda/chirpy/internal/auth"
)
func (cfg *apiConfig) HandlerUpgradeUserToChirpyRed(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Event string `json:"event"`
Data struct {
UserID uuid.UUID `json:"user_id"`
} `json:"data"`
}
apiKey, err := auth.GetAPIKey(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't find api key", err)
return
}
if apiKey != cfg.polkaKey {
respondWithError(w, http.StatusUnauthorized, "Invalid API key", err)
return
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
if err := decoder.Decode(¶ms); err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters", err)
return
}
if params.Event != "user.upgraded" {
w.WriteHeader(http.StatusNoContent)
return
}
if err := cfg.db.UpgradeUserToChirpyRed(r.Context(), params.Data.UserID); err != nil {
if errors.Is(err, sql.ErrNoRows) {
respondWithError(w, http.StatusNotFound, "Couldn't find user", err)
}
respondWithError(w, http.StatusInternalServerError, "Couldn't upgrade user", err)
return
}
w.WriteHeader(http.StatusNoContent)
}