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

65 lines
1.5 KiB
Go
Raw Normal View History

2020-10-25 09:22:10 +03:00
package services
import (
"github.com/jinzhu/gorm"
2020-10-26 05:00:24 +03:00
"github.com/muety/wakapi/config"
2020-10-25 09:22:10 +03:00
"github.com/muety/wakapi/models"
"github.com/patrickmn/go-cache"
"time"
2020-10-25 09:22:10 +03:00
)
type CustomRuleService struct {
2020-10-26 05:00:24 +03:00
Config *config.Config
2020-10-25 09:22:10 +03:00
Db *gorm.DB
cache *cache.Cache
2020-10-25 09:22:10 +03:00
}
func NewCustomRuleService(db *gorm.DB) *CustomRuleService {
return &CustomRuleService{
2020-10-26 05:00:24 +03:00
Config: config.Get(),
2020-10-25 09:22:10 +03:00
Db: db,
cache: cache.New(1*time.Hour, 2*time.Hour),
2020-10-25 09:22:10 +03:00
}
}
2020-10-26 05:00:24 +03:00
func (srv *CustomRuleService) GetCustomRuleById(customRuleId uint) (*models.CustomRule, error) {
2020-10-25 09:22:10 +03:00
r := &models.CustomRule{}
2020-10-26 05:00:24 +03:00
if err := srv.Db.Where(&models.CustomRule{ID: customRuleId}).First(r).Error; err != nil {
2020-10-25 09:22:10 +03:00
return r, err
}
return r, nil
}
func (srv *CustomRuleService) GetCustomRuleForUser(userId string) ([]*models.CustomRule, error) {
var rules []*models.CustomRule
if rules, found := srv.cache.Get(userId); found {
2020-10-27 00:34:50 +03:00
return rules.([]*models.CustomRule), nil
}
2020-10-25 09:22:10 +03:00
if err := srv.Db.
Where(&models.CustomRule{UserID: userId}).
Find(&rules).Error; err != nil {
return rules, err
}
srv.cache.Set(userId, rules, cache.DefaultExpiration)
2020-10-25 09:22:10 +03:00
return rules, nil
}
func (srv *CustomRuleService) Create(rule *models.CustomRule) (*models.CustomRule, error) {
result := srv.Db.Create(rule)
if err := result.Error; err != nil {
return nil, err
}
srv.cache.Delete(rule.UserID)
2020-10-25 09:22:10 +03:00
return rule, nil
}
func (srv *CustomRuleService) Delete(rule *models.CustomRule) {
srv.Db.
Where("id = ?", rule.ID).
Where("user_id = ?", rule.UserID).
Delete(models.CustomRule{})
srv.cache.Delete(rule.UserID)
2020-10-25 09:22:10 +03:00
}