Files
pulse-api/internal/handler/profile.go

73 lines
1.7 KiB
Go

package handler
import (
"encoding/json"
"net/http"
"github.com/daniil/homelab-api/internal/middleware"
"github.com/daniil/homelab-api/internal/model"
"github.com/daniil/homelab-api/internal/repository"
)
type ProfileHandler struct {
userRepo *repository.UserRepository
}
func NewProfileHandler(userRepo *repository.UserRepository) *ProfileHandler {
return &ProfileHandler{userRepo: userRepo}
}
func (h *ProfileHandler) Get(w http.ResponseWriter, r *http.Request) {
userID := middleware.GetUserID(r.Context())
user, err := h.userRepo.GetByID(userID)
if err != nil {
writeError(w, "user not found", http.StatusNotFound)
return
}
user.ProcessForJSON()
// Return only profile fields
profile := map[string]interface{}{
"telegram_chat_id": user.TelegramChatIDValue,
"notifications_enabled": user.NotificationsEnabled,
"timezone": user.Timezone,
}
writeJSON(w, profile, http.StatusOK)
}
func (h *ProfileHandler) Update(w http.ResponseWriter, r *http.Request) {
userID := middleware.GetUserID(r.Context())
var req model.UpdateProfileRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeError(w, "invalid request body", http.StatusBadRequest)
return
}
err := h.userRepo.UpdateProfile(userID, &req)
if err != nil {
writeError(w, "failed to update profile", http.StatusInternalServerError)
return
}
// Get updated user
user, err := h.userRepo.GetByID(userID)
if err != nil {
writeError(w, "user not found", http.StatusNotFound)
return
}
user.ProcessForJSON()
profile := map[string]interface{}{
"telegram_chat_id": user.TelegramChatIDValue,
"notifications_enabled": user.NotificationsEnabled,
"timezone": user.Timezone,
}
writeJSON(w, profile, http.StatusOK)
}