happy/web/mood_handlers.go

73 lines
1.8 KiB
Go

package web
import (
"encoding/json"
"fmt"
"net/http"
"code.chrissexton.org/cws/happy/mood"
"github.com/rs/zerolog/log"
)
func (web *Web) getMoods(w http.ResponseWriter, r *http.Request) {
log.Debug().Interface("req", r).Msg("getMoods")
q := `select mc.id category_id,mc.name category_name,mct.key,mct.value
from mood_categories mc
inner join mood_category_texts mct
on mc.id=mct.mood_category_id`
recs := []mood.GetMoodsResponse{}
err := web.db.Select(&recs, q)
if err != nil {
log.Error().Err(err).Msg("could not retrieve mood categories and texts")
w.WriteHeader(500)
fmt.Fprintf(w, "Error getting moods: %s", err)
return
}
resp, err := json.Marshal(recs)
if err != nil {
log.Error().Err(err).Msg("error from json.Marshal")
w.WriteHeader(500)
fmt.Fprintf(w, "Error getting moods: %s", err)
return
}
fmt.Fprintf(w, "%s", string(resp))
}
func (web *Web) handleMood(w http.ResponseWriter, r *http.Request) {
uid := r.Header.Get("X-user-id")
verify := r.Header.Get("X-user-verification")
log.Debug().
Str("uid", uid).
Str("verify", verify).
Msg("handleMood")
dec := json.NewDecoder(r.Body)
happyReq := mood.GetMoodsResponse{}
err := dec.Decode(&happyReq)
if err != nil {
log.Error().Err(err).Msg("error with happy")
w.WriteHeader(400)
fmt.Fprintf(w, err.Error())
return
}
log.Debug().
Interface("mood", happyReq).
Msg("mood")
user, err := web.uf.FromStr(uid, verify)
if err != nil {
log.Error().
Err(err).
Msg("error getting user")
w.WriteHeader(403)
fmt.Fprintf(w, "Error: %s", err)
return
}
if err := web.mood.RecordMood(happyReq, user); err != nil {
log.Error().Err(err).Msg("error saving mood")
w.WriteHeader(500)
fmt.Fprintf(w, "Error: %s", err)
return
}
fmt.Fprintf(w, "ok")
}