lots of stuff, don't truly remember
This commit is contained in:
63
internal/nutrition/handler.go
Normal file
63
internal/nutrition/handler.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package nutrition
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"rideaware/internal/config"
|
||||
"rideaware/internal/middleware"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
service *Service
|
||||
}
|
||||
|
||||
func NewHandler() *Handler {
|
||||
return &Handler{
|
||||
service: NewService(),
|
||||
}
|
||||
}
|
||||
|
||||
// GetTargets GET /api/protected/nutrition/targets
|
||||
func (h *Handler) GetTargets(w http.ResponseWriter, r *http.Request) {
|
||||
claims := r.Context().Value(middleware.UserContextKey).(*config.CustomClaims)
|
||||
if claims == nil {
|
||||
respondError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
targets, err := h.service.GetTargets(claims.UserID)
|
||||
if err != nil {
|
||||
respondError(w, http.StatusInternalServerError, "failed to calculate targets")
|
||||
return
|
||||
}
|
||||
|
||||
respondJSON(w, http.StatusOK, targets)
|
||||
}
|
||||
|
||||
// GetWeekly GET /api/protected/nutrition/weekly
|
||||
func (h *Handler) GetWeekly(w http.ResponseWriter, r *http.Request) {
|
||||
claims := r.Context().Value(middleware.UserContextKey).(*config.CustomClaims)
|
||||
if claims == nil {
|
||||
respondError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
|
||||
weekly, err := h.service.GetWeeklyNutrition(claims.UserID)
|
||||
if err != nil {
|
||||
respondError(w, http.StatusInternalServerError, "failed to calculate weekly nutrition")
|
||||
return
|
||||
}
|
||||
|
||||
respondJSON(w, http.StatusOK, weekly)
|
||||
}
|
||||
|
||||
func respondJSON(w http.ResponseWriter, status int, data interface{}) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(data)
|
||||
}
|
||||
|
||||
func respondError(w http.ResponseWriter, status int, message string) {
|
||||
respondJSON(w, status, map[string]string{"error": message})
|
||||
}
|
||||
Reference in New Issue
Block a user