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

Add summary cache.

This commit is contained in:
Ferdinand Mütsch 2019-05-19 20:14:57 +02:00
parent a157edd03b
commit d5253ba46b

View File

@ -16,6 +16,8 @@ const (
IntervalLastYear string = "year" IntervalLastYear string = "year"
) )
var summaryCache map[time.Time]*models.Summary
type SummaryHandler struct { type SummaryHandler struct {
SummarySrvc *services.SummaryService SummarySrvc *services.SummaryService
} }
@ -26,6 +28,8 @@ func (h *SummaryHandler) Get(w http.ResponseWriter, r *http.Request) {
return return
} }
tryInitCache()
user := r.Context().Value(models.UserKey).(*models.User) user := r.Context().Value(models.UserKey).(*models.User)
params := r.URL.Query() params := r.URL.Query()
from, err := utils.ParseDate(params.Get("from")) from, err := utils.ParseDate(params.Get("from"))
@ -47,11 +51,22 @@ func (h *SummaryHandler) Get(w http.ResponseWriter, r *http.Request) {
} }
} }
summary, err := h.SummarySrvc.GetSummary(from, utils.StartOfDay(), user) if _, ok := summaryCache[from]; !ok {
if err != nil { // Cache Miss
w.WriteHeader(http.StatusInternalServerError) summary, err := h.SummarySrvc.GetSummary(from, utils.StartOfDay(), user) // 'to' is always constant
return if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
summaryCache[from] = summary
} }
summary, _ := summaryCache[from]
utils.RespondJSON(w, http.StatusOK, summary) utils.RespondJSON(w, http.StatusOK, summary)
} }
func tryInitCache() {
if summaryCache == nil {
summaryCache = make(map[time.Time]*models.Summary)
}
}