more refactoring into seperate handlers
This commit is contained in:
@@ -2,8 +2,6 @@ package stacks
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"screenmark/screenmark/middleware"
|
||||
@@ -13,45 +11,11 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func writeJsonOrError[K any](logger *log.Logger, object K, w http.ResponseWriter) {
|
||||
jsonObject, err := json.Marshal(object)
|
||||
if err != nil {
|
||||
logger.Warn("could not marshal json object", "err", err)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
w.Write(jsonObject)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
type StackHandler struct {
|
||||
logger *log.Logger
|
||||
stackModel models.ListModel
|
||||
}
|
||||
|
||||
func withValidatedPost[K any](
|
||||
fn func(request K, w http.ResponseWriter, r *http.Request),
|
||||
) func(w http.ResponseWriter, r *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
request := new(K)
|
||||
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err = json.Unmarshal(body, request)
|
||||
if err != nil {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
fn(*request, w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *StackHandler) getAllStacks(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
@@ -67,7 +31,7 @@ func (h *StackHandler) getAllStacks(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
writeJsonOrError(h.logger, lists, w)
|
||||
middleware.WriteJsonOrError(h.logger, lists, w)
|
||||
}
|
||||
|
||||
func (h *StackHandler) getStackItems(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -91,7 +55,7 @@ func (h *StackHandler) getStackItems(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
writeJsonOrError(h.logger, lists, w)
|
||||
middleware.WriteJsonOrError(h.logger, lists, w)
|
||||
}
|
||||
|
||||
type EditStack struct {
|
||||
@@ -136,9 +100,8 @@ func (h *StackHandler) CreateRoutes(r chi.Router) {
|
||||
r.Get("/", h.getAllStacks)
|
||||
r.Get("/{listID}", h.getStackItems)
|
||||
|
||||
r.Post("/", withValidatedPost(h.createStack))
|
||||
|
||||
r.Patch("/{listID}", withValidatedPost(h.editStack))
|
||||
r.Post("/", middleware.WithValidatedPost(h.createStack))
|
||||
r.Patch("/{listID}", middleware.WithValidatedPost(h.editStack))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user