-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
113 lines (98 loc) · 2.55 KB
/
service.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package flags
import (
"strconv"
"github.com/markelca/toggles/pkg/storage"
)
const (
redisKeyPrefix = "flag:"
)
type FlagService interface {
Get(key string) (bool, error)
Create(f Flag) error
Update(name string, value bool) error
Exists(key string) (bool, error)
List() ([]Flag, error)
Delete(name string) error
}
type DefaultFlagService struct {
repository FlagRepository
cacheClient storage.CacheClient
}
func NewFlagService(cacheClient storage.CacheClient, repository FlagRepository) FlagService {
return DefaultFlagService{repository, cacheClient}
}
func (flagService DefaultFlagService) Get(key string) (bool, error) {
cachedResult, err := flagService.cacheClient.Get(redisKeyPrefix + key)
if err == nil {
// We update the TTL on every successfull key access
err = flagService.cacheClient.Expire(redisKeyPrefix+key, storage.DEFAULT_EXPIRATION_TIME)
if err != nil {
return false, nil
}
} else if err == storage.Nil {
value, err := flagService.repository.Get(key)
if err == nil {
flagService.cacheClient.Set(redisKeyPrefix+key, value, storage.DEFAULT_EXPIRATION_TIME)
}
return value, err
} else if err != nil {
return false, err
}
result, err := strconv.ParseBool(cachedResult)
if err != nil {
return false, err
}
return result, nil
}
func (flagService DefaultFlagService) Create(f Flag) error {
exists, err := flagService.Exists(f.Name)
if err != nil {
return err
} else if exists {
return ErrFlagAlreadyExists
}
err = flagService.repository.Set(f.Name, f.Value)
if err != nil {
return err
}
return nil
}
func (flagService DefaultFlagService) Update(name string, value bool) error {
exists, err := flagService.Exists(name)
if err != nil {
return err
} else if !exists {
return ErrFlagNotFound
}
err = flagService.repository.Set(name, value)
if err != nil {
return err
} else {
err = flagService.cacheClient.Delete(redisKeyPrefix + name)
return err
}
}
func (flagService DefaultFlagService) Exists(key string) (bool, error) {
return flagService.repository.Exists(key)
}
func (flagService DefaultFlagService) List() ([]Flag, error) {
flags, err := flagService.repository.List()
if err != nil {
return nil, err
}
return flags, nil
}
func (flagService DefaultFlagService) Delete(name string) error {
if exists, err := flagService.Exists(name); err != nil {
return err
} else if !exists {
return ErrFlagNotFound
}
if err := flagService.repository.Delete(name); err != nil {
return err
}
if err := flagService.cacheClient.Delete(redisKeyPrefix + name); err != nil {
return err
}
return nil
}