fix: more refactoring #181

This commit is contained in:
2024-10-20 15:02:39 +02:00
parent 38d530a3c9
commit 77bf66a4fc
6 changed files with 153 additions and 56 deletions

View File

@@ -1,15 +1,17 @@
package handler
import (
"log/slog"
"me-fit/service"
"me-fit/template"
"me-fit/template/workout"
"me-fit/types"
"me-fit/utils"
"time"
"strconv"
"database/sql"
"net/http"
"time"
)
type HandlerWorkout interface {
@@ -35,8 +37,8 @@ func NewHandlerWorkout(db *sql.DB, service service.ServiceWorkout, auth service.
func (handler HandlerWorkoutImpl) handle(router *http.ServeMux) {
router.Handle("/workout", handler.handleWorkoutPage())
router.Handle("POST /api/workout", handler.handleAddWorkout())
router.Handle("GET /api/workout", service.HandleWorkoutGetComp(handler.db))
router.Handle("DELETE /api/workout/{id}", service.HandleWorkoutDeleteComp(handler.db))
router.Handle("GET /api/workout", handler.handleGetWorkout())
router.Handle("DELETE /api/workout/{id}", handler.handleDeleteWorkout())
}
func (handler HandlerWorkoutImpl) handleWorkoutPage() http.HandlerFunc {
@@ -88,3 +90,59 @@ func (handler HandlerWorkoutImpl) handleAddWorkout() http.HandlerFunc {
}
}
}
func (handler HandlerWorkoutImpl) handleGetWorkout() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, err := handler.auth.GetUserFromSessionId(utils.GetSessionID(r))
if err != nil {
utils.DoRedirect(w, r, "/auth/signin")
return
}
workouts, err := handler.service.GetWorkouts(user)
if err != nil {
return
}
wos := make([]workout.Workout, 0)
for _, wo := range workouts {
wos = append(wos, workout.Workout{Id: wo.RowId, Date: wo.Date, Type: wo.Type, Sets: wo.Sets, Reps: wo.Reps})
}
workout.WorkoutListComp(wos).Render(r.Context(), w)
}
}
func (handler HandlerWorkoutImpl) handleDeleteWorkout() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, err := handler.auth.GetUserFromSessionId(utils.GetSessionID(r))
if err != nil {
utils.DoRedirect(w, r, "/auth/signin")
return
}
rowId := r.PathValue("id")
if rowId == "" {
http.Error(w, "Missing required fields", http.StatusBadRequest)
slog.Warn("Missing required fields for workout delete")
utils.TriggerToast(w, r, "error", "Missing ID field")
return
}
rowIdInt, err := strconv.Atoi(rowId)
if err != nil {
http.Error(w, "Invalid ID", http.StatusBadRequest)
slog.Warn("Invalid ID for workout delete")
utils.TriggerToast(w, r, "error", "Invalid ID")
return
}
err = handler.service.DeleteWorkout(user, rowIdInt)
if err != nil {
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
slog.Error("Could not delete workout", err)
utils.TriggerToast(w, r, "error", "Internal Server Error")
return
}
}
}