mirror of
https://github.com/muety/wakapi.git
synced 2023-08-10 21:12:56 +03:00
Cache rules per user, invalidate cache on update
This commit is contained in:
parent
178c417757
commit
86fc751e58
@ -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
|
||||
|
@ -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)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user