2021-08-29 16:37:20 +02:00
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"git.snrd.de/Spaenny/goddit"
|
2021-08-29 17:09:48 +02:00
|
|
|
"github.com/alexedwards/scs/v2"
|
2021-08-29 16:37:20 +02:00
|
|
|
"github.com/go-chi/chi"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
)
|
|
|
|
|
|
|
|
type CommentHandler struct {
|
2021-08-29 17:09:48 +02:00
|
|
|
store goddit.Store
|
|
|
|
sessions *scs.SessionManager
|
2021-08-29 16:37:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func (h *CommentHandler) Store() http.HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
content := r.FormValue("content")
|
|
|
|
idStr := chi.URLParam(r, "postID")
|
|
|
|
|
|
|
|
id, err := uuid.Parse(idStr)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := h.store.CreateComment(&goddit.Comment{
|
|
|
|
ID: uuid.New(),
|
|
|
|
PostID: id,
|
|
|
|
Content: content,
|
|
|
|
}); err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
http.Redirect(w, r, r.Referer(), http.StatusFound)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *CommentHandler) Vote() http.HandlerFunc {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
idStr := chi.URLParam(r, "id")
|
|
|
|
|
|
|
|
id, err := uuid.Parse(idStr)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
c, err := h.store.Comment(id)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
dir := r.URL.Query().Get("dir")
|
|
|
|
if dir == "up" {
|
|
|
|
c.Votes++
|
|
|
|
} else if dir == "down" {
|
|
|
|
c.Votes--
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := h.store.UpdateComment(&c); err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
http.Redirect(w, r, r.Referer(), http.StatusFound)
|
|
|
|
}
|
|
|
|
}
|