Delete chirps

This commit is contained in:
2025-03-11 23:04:05 +02:00
parent 704393e0e4
commit bad1d140ee
3 changed files with 68 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.28.0
// source: DeleteChirpByID.sql
package database
import (
"context"
"github.com/google/uuid"
)
const deleteChirpByID = `-- name: DeleteChirpByID :exec
DELETE FROM chirps WHERE id = $1
`
func (q *Queries) DeleteChirpByID(ctx context.Context, id uuid.UUID) error {
_, err := q.db.ExecContext(ctx, deleteChirpByID, id)
return err
}

45
main.go
View File

@@ -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))

View File

@@ -0,0 +1,2 @@
-- name: DeleteChirpByID :exec
DELETE FROM chirps WHERE id = $1;