1
0
mirror of https://github.com/muety/wakapi.git synced 2023-08-10 21:12:56 +03:00
wakapi/routes/summary.go

94 lines
2.0 KiB
Go
Raw Normal View History

package routes
import (
2019-05-19 21:34:26 +03:00
"crypto/md5"
"net/http"
2019-05-19 21:34:26 +03:00
"strconv"
"time"
"github.com/n1try/wakapi/models"
"github.com/n1try/wakapi/services"
"github.com/n1try/wakapi/utils"
)
2019-05-19 21:06:07 +03:00
const (
IntervalLastDay string = "day"
IntervalLastWeek string = "week"
IntervalLastMonth string = "month"
IntervalLastYear string = "year"
)
2019-05-19 21:34:26 +03:00
var summaryCache map[string]*models.Summary
2019-05-19 21:14:57 +03:00
type SummaryHandler struct {
SummarySrvc *services.SummaryService
}
func (h *SummaryHandler) Get(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
2019-05-19 21:14:57 +03:00
tryInitCache()
user := r.Context().Value(models.UserKey).(*models.User)
params := r.URL.Query()
from, err := utils.ParseDate(params.Get("from"))
if err != nil {
2019-05-19 21:06:07 +03:00
interval := params.Get("interval")
switch interval {
case IntervalLastDay:
from = utils.StartOfDay().Add(-24 * time.Hour)
case IntervalLastWeek:
from = utils.StartOfWeek()
case IntervalLastMonth:
from = utils.StartOfMonth()
case IntervalLastYear:
from = utils.StartOfYear()
default:
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Missing 'from' parameter"))
return
}
}
2019-05-19 21:34:26 +03:00
live := params.Get("live") != "" && params.Get("live") != "false"
to := utils.StartOfDay()
if live {
to = time.Now()
}
var summary *models.Summary
cacheKey := getHash([]time.Time{from, to})
if _, ok := summaryCache[cacheKey]; !ok {
2019-05-19 21:14:57 +03:00
// Cache Miss
2019-05-19 21:34:26 +03:00
summary, err = h.SummarySrvc.GetSummary(from, to, user) // 'to' is always constant
2019-05-19 21:14:57 +03:00
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
2019-05-19 21:34:26 +03:00
if !live {
summaryCache[cacheKey] = summary
}
} else {
summary, _ = summaryCache[cacheKey]
}
utils.RespondJSON(w, http.StatusOK, summary)
}
2019-05-19 21:14:57 +03:00
func tryInitCache() {
if summaryCache == nil {
2019-05-19 21:34:26 +03:00
summaryCache = make(map[string]*models.Summary)
}
}
func getHash(times []time.Time) string {
digest := md5.New()
for _, t := range times {
digest.Write([]byte(strconv.Itoa(int(t.Unix()))))
2019-05-19 21:14:57 +03:00
}
2019-05-19 21:34:26 +03:00
return string(digest.Sum(nil))
2019-05-19 21:14:57 +03:00
}