-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenum.go
70 lines (55 loc) · 1.38 KB
/
enum.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
package kredis
import (
"errors"
"time"
)
type Enum struct {
Proxy
defaultValue string
values map[string]bool
}
var EnumEmptyValues = errors.New("values cannot be empty")
var EnumExpiryNotSupported = errors.New("cannot use WithExpiry with Enum")
var EnumInvalidValue = errors.New("invalid enum value")
func NewEnum(key string, defaultValue string, values []string, opts ...ProxyOption) (*Enum, error) {
if len(values) == 0 {
return nil, EnumEmptyValues
}
proxy, err := NewProxy(key, opts...)
if err != nil {
return nil, err
}
if proxy.expiresIn != 0 {
return nil, EnumExpiryNotSupported
}
enum := &Enum{Proxy: *proxy, defaultValue: defaultValue, values: map[string]bool{}}
for _, value := range values {
enum.values[value] = true
}
err = enum.SetValue(defaultValue)
if err != nil {
return nil, err
}
return enum, nil
}
func (e *Enum) Is(value string) bool {
return e.Value() == value
}
func (e *Enum) Value() string {
value, _ := e.client.Get(e.ctx, e.key).Result()
return value
}
func (e *Enum) SetValue(value string) error {
if _, ok := e.values[value]; !ok {
return EnumInvalidValue
}
_, err := e.client.Set(e.ctx, e.key, value, time.Duration(0)).Result()
return err
}
func (e *Enum) Reset() (err error) {
pipe := e.client.TxPipeline()
pipe.Del(e.ctx, e.key)
pipe.Set(e.ctx, e.key, e.defaultValue, time.Duration(0))
_, err = pipe.Exec(e.ctx)
return
}