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

Refactor to server-rendered app.

This commit is contained in:
Ferdinand Mütsch
2020-02-20 14:28:55 +01:00
parent d583dd312b
commit b7f700e7a5
14 changed files with 405 additions and 329 deletions

View File

@ -28,6 +28,8 @@ type AggregationJob struct {
To time.Time
}
func (srv *AggregationService) Init() {}
// Schedule a job to (re-)generate summaries every day shortly after midnight
// TODO: Make configurable
func (srv *AggregationService) Schedule() {

View File

@ -15,6 +15,8 @@ type AliasService struct {
var userAliases sync.Map
func (srv *AliasService) Init() {}
func (srv *AliasService) LoadUserAliases(userId string) error {
var aliases []*models.Alias
if err := srv.Db.

5
services/common.go Normal file
View File

@ -0,0 +1,5 @@
package services
type Initializable interface {
Init()
}

View File

@ -15,6 +15,8 @@ type HeartbeatService struct {
Db *gorm.DB
}
func (srv *HeartbeatService) Init() {}
func (srv *HeartbeatService) InsertBatch(heartbeats []*models.Heartbeat) error {
var batch []interface{}
for _, h := range heartbeats {

View File

@ -1,9 +1,12 @@
package services
import (
"crypto/md5"
"errors"
"github.com/patrickmn/go-cache"
"math"
"sort"
"strconv"
"time"
"github.com/jinzhu/gorm"
@ -12,6 +15,7 @@ import (
type SummaryService struct {
Config *models.Config
Cache *cache.Cache
Db *gorm.DB
HeartbeatService *HeartbeatService
AliasService *AliasService
@ -22,11 +26,21 @@ type Interval struct {
End time.Time
}
func (srv *SummaryService) Init() {
srv.Cache = cache.New(24*time.Hour, 24*time.Hour)
}
func (srv *SummaryService) Construct(from, to time.Time, user *models.User, recompute bool) (*models.Summary, error) {
var existingSummaries []*models.Summary
var cacheKey string
if recompute {
existingSummaries = make([]*models.Summary, 0)
} else {
cacheKey = getHash([]time.Time{from, to}, user)
if result, ok := srv.Cache.Get(cacheKey); ok {
return result.(*models.Summary), nil
}
summaries, err := srv.GetByUserWithin(user, from, to)
if err != nil {
return nil, err
@ -94,6 +108,10 @@ func (srv *SummaryService) Construct(from, to time.Time, user *models.User, reco
return nil, err
}
if cacheKey != "" {
srv.Cache.SetDefault(cacheKey, summary)
}
return summary, nil
}
@ -283,3 +301,12 @@ func mergeSummaryItems(existing []*models.SummaryItem, new []*models.SummaryItem
return itemList
}
func getHash(times []time.Time, user *models.User) string {
digest := md5.New()
for _, t := range times {
digest.Write([]byte(strconv.Itoa(int(t.Unix()))))
}
digest.Write([]byte(user.ID))
return string(digest.Sum(nil))
}

View File

@ -10,6 +10,8 @@ type UserService struct {
Db *gorm.DB
}
func (srv *UserService) Init() {}
func (srv *UserService) GetUserById(userId string) (*models.User, error) {
u := &models.User{}
if err := srv.Db.Where(&models.User{ID: userId}).First(u).Error; err != nil {