From 86fc751e5860be5a6d54d98fe68adebdd0fb9c60 Mon Sep 17 00:00:00 2001 From: Roch D'Amour Date: Sun, 25 Oct 2020 23:19:16 -0400 Subject: [PATCH] Cache rules per user, invalidate cache on update --- docker-compose.yml | 2 +- services/custom_rule.go | 12 +++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index 36ce414..275c6df 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,7 +13,7 @@ services: WAKAPI_DB_PASSWORD: "asdfasdfasdf" WAKAPI_DB_HOST: "db" WAKAPI_DB_PORT: "5432" - ENV: "dev" + ENVIRONMENT: "dev" db: image: postgres:12.3 diff --git a/services/custom_rule.go b/services/custom_rule.go index be0784d..58c0079 100644 --- a/services/custom_rule.go +++ b/services/custom_rule.go @@ -4,17 +4,21 @@ import ( "github.com/jinzhu/gorm" "github.com/muety/wakapi/config" "github.com/muety/wakapi/models" + "github.com/patrickmn/go-cache" + "time" ) type CustomRuleService struct { Config *config.Config Db *gorm.DB + cache *cache.Cache } func NewCustomRuleService(db *gorm.DB) *CustomRuleService { return &CustomRuleService{ Config: config.Get(), Db: db, + cache: cache.New(1*time.Hour, 2*time.Hour), } } @@ -28,12 +32,16 @@ func (srv *CustomRuleService) GetCustomRuleById(customRuleId uint) (*models.Cust func (srv *CustomRuleService) GetCustomRuleForUser(userId string) ([]*models.CustomRule, error) { var rules []*models.CustomRule + if rules, found := srv.cache.Get(userId); found { + return rules.([]*models.CustomRule), nil; + } + if err := srv.Db. Where(&models.CustomRule{UserID: userId}). Find(&rules).Error; err != nil { return rules, err } - + srv.cache.Set(userId, rules, cache.DefaultExpiration) return rules, nil } @@ -42,6 +50,7 @@ func (srv *CustomRuleService) Create(rule *models.CustomRule) (*models.CustomRul if err := result.Error; err != nil { return nil, err } + srv.cache.Delete(rule.UserID) return rule, nil } @@ -51,4 +60,5 @@ func (srv *CustomRuleService) Delete(rule *models.CustomRule) { Where("id = ?", rule.ID). Where("user_id = ?", rule.UserID). Delete(models.CustomRule{}) + srv.cache.Delete(rule.UserID) }