This commit is contained in:
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/internal/auth"
|
||||
"git.schreifuchs.ch/schreifuchs/ng-blog/internal/model"
|
||||
"github.com/google/uuid"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
@@ -28,6 +29,13 @@ func (s Service) SavePost(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if post.Private {
|
||||
secret := uuid.NewString()
|
||||
post.Secret = &secret
|
||||
} else {
|
||||
post.Secret = nil
|
||||
}
|
||||
|
||||
post.UserID = claims.UserID
|
||||
|
||||
if err := s.db.Save(&post).Error; err != nil {
|
||||
@@ -50,13 +58,56 @@ func (s Service) SavePost(w http.ResponseWriter, r *http.Request) {
|
||||
func (s Service) GetAllPosts(w http.ResponseWriter, r *http.Request) {
|
||||
var posts []model.Post
|
||||
|
||||
claims, ok := auth.ExtractClaims(r.Context())
|
||||
if !ok {
|
||||
claims = nil
|
||||
}
|
||||
|
||||
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)
|
||||
newPosts := make([]model.Post, 0, len(posts))
|
||||
for _, p := range posts {
|
||||
if p.Secret == nil {
|
||||
newPosts = append(newPosts, p)
|
||||
continue
|
||||
}
|
||||
if claims == nil {
|
||||
continue
|
||||
}
|
||||
if claims.UserID == p.UserID {
|
||||
newPosts = append(newPosts, p)
|
||||
}
|
||||
}
|
||||
|
||||
res, err := json.Marshal(&newPosts)
|
||||
if err != nil {
|
||||
fmt.Fprint(w, err.Error())
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Write(res)
|
||||
}
|
||||
|
||||
// GetPostBySecret retrieves a post by its secret from the database, eager-loads comments, and returns it as JSON.
|
||||
func (s Service) GetPostBySecret(w http.ResponseWriter, r *http.Request) {
|
||||
secret, ok := mux.Vars(r)["secret"]
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
var post model.Post
|
||||
if err := s.db.Preload("Comments").Where("secret = ?", secret).First(&post).Error; err != nil {
|
||||
fmt.Fprint(w, err.Error())
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
res, err := json.Marshal(&post)
|
||||
if err != nil {
|
||||
fmt.Fprint(w, err.Error())
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
|
||||
Reference in New Issue
Block a user