Delete chirps
This commit is contained in:
45
main.go
45
main.go
@@ -139,6 +139,50 @@ func getChirpByIDHandler(cfg *apiConfig) http.HandlerFunc {
|
||||
}
|
||||
}
|
||||
|
||||
func deleteChirpByIDHandler(cfg *apiConfig) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
token, err := auth.GetBearerToken(r.Header)
|
||||
if err != nil {
|
||||
httpResponse.JSONHandler(w, http.StatusUnauthorized, `{"error": "Unauthorized"}`)
|
||||
return
|
||||
}
|
||||
|
||||
userId, err := auth.ValidateJWT(token, cfg.secret)
|
||||
|
||||
_, err = cfg.db.GetUserByID(context.Background(), userId)
|
||||
if err != nil {
|
||||
httpResponse.JSONHandler(w, http.StatusUnauthorized, `{"error": "Unauthorized"}`)
|
||||
return
|
||||
}
|
||||
|
||||
chirpID, err := uuid.Parse(r.PathValue("chirpID"))
|
||||
if err != nil {
|
||||
httpResponse.JSONHandler(w, http.StatusBadRequest, `{"error": "InvalidChirpID"}`)
|
||||
return
|
||||
}
|
||||
|
||||
chirp, err := cfg.db.GetChirpByID(context.Background(), chirpID)
|
||||
if err != nil {
|
||||
httpResponse.JSONHandler(w, http.StatusNotFound, `{"error": "ChirpNotFound"}`)
|
||||
return
|
||||
}
|
||||
|
||||
if chirp.UserID != userId {
|
||||
httpResponse.JSONHandler(w, http.StatusForbidden, `{"error": "Forbidden"}`)
|
||||
return
|
||||
}
|
||||
|
||||
err = cfg.db.DeleteChirpByID(context.Background(), chirp.ID)
|
||||
if err != nil {
|
||||
httpResponse.SomethingWentWrong(w)
|
||||
return
|
||||
}
|
||||
|
||||
httpResponse.PlainTextHandler(w, http.StatusNoContent, "")
|
||||
}
|
||||
}
|
||||
|
||||
func updateUserDatahandler(cfg *apiConfig) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
type parameters struct {
|
||||
@@ -477,6 +521,7 @@ func main() {
|
||||
mux.HandleFunc("POST /api/chirps", postChirpsHandler(apiCfg))
|
||||
mux.HandleFunc("GET /api/chirps", getAllChirpsHandler(apiCfg))
|
||||
mux.HandleFunc("GET /api/chirps/{chirpID}", getChirpByIDHandler(apiCfg))
|
||||
mux.HandleFunc("DELETE /api/chirps/{chirpID}", deleteChirpByIDHandler(apiCfg))
|
||||
mux.HandleFunc("PUT /api/users", updateUserDatahandler(apiCfg))
|
||||
|
||||
mux.HandleFunc("GET /admin/metrics", adminMetricsHandler(apiCfg))
|
||||
|
||||
Reference in New Issue
Block a user