Files
ng-blog/internal/posts/controller.go
2025-05-05 10:00:50 +02:00

94 lines
2.3 KiB
Go

package posts
import (
"encoding/json"
"fmt"
"log"
"net/http"
"strconv"
"git.schreifuchs.ch/schreifuchs/ng-blog/internal/auth"
"git.schreifuchs.ch/schreifuchs/ng-blog/internal/model"
"github.com/gorilla/mux"
)
// SavePost handles saving a new post to the database after extracting user claims and decoding the request body.
func (s Service) SavePost(w http.ResponseWriter, r *http.Request) {
claims, ok := auth.ExtractClaims(r.Context())
if !ok {
log.Println("Err could not ExtractClaims")
w.WriteHeader(http.StatusInternalServerError)
return
}
var post model.Post
if err := json.NewDecoder(r.Body).Decode(&post); err != nil {
fmt.Fprint(w, err.Error())
w.WriteHeader(http.StatusBadRequest)
return
}
post.UserID = claims.UserID
if err := s.db.Save(&post).Error; err != nil {
fmt.Fprint(w, err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
res, err := json.Marshal(&post)
if err != nil {
fmt.Fprint(w, err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(res)
}
// GetAllPosts retrieves all posts from the database, eager-loads comments, orders them by creation time, and returns them as JSON.
func (s Service) GetAllPosts(w http.ResponseWriter, r *http.Request) {
var posts []model.Post
if err := s.db.Preload("Comments").Order("created_at DESC").Find(&posts).Error; err != nil {
fmt.Fprint(w, err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
res, err := json.Marshal(&posts)
if err != nil {
fmt.Fprint(w, err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Write(res)
}
// DeletePost handles deleting a post from the database based on its ID and user authentication.
func (s Service) DeletePost(w http.ResponseWriter, r *http.Request) {
idStr, ok := mux.Vars(r)["postID"]
if !ok {
w.WriteHeader(http.StatusNotFound)
return
}
id, err := strconv.Atoi(idStr)
if err != nil {
w.WriteHeader(http.StatusNotFound)
return
}
claims, ok := auth.ExtractClaims(r.Context())
if !ok {
log.Println("Err could not ExtractClaims")
w.WriteHeader(http.StatusInternalServerError)
return
}
err = s.db.Where("user_id = ?", claims.UserID).Delete(&model.Post{}, id).Error
if err != nil {
fmt.Fprint(w, err.Error())
w.WriteHeader(http.StatusInternalServerError)
}
w.WriteHeader(http.StatusNoContent)
}