/
store_redis.go
102 lines (88 loc) · 2.47 KB
/
store_redis.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
package anonymous
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
goredis "github.com/go-redis/redis/v8"
"github.com/authgear/authgear-server/pkg/lib/config"
"github.com/authgear/authgear-server/pkg/lib/infra/redis/appredis"
"github.com/authgear/authgear-server/pkg/util/clock"
)
var ErrPromotionCodeNotFound = errors.New("promotion code not found")
type StoreRedis struct {
Context context.Context
Redis *appredis.Handle
AppID config.AppID
Clock clock.Clock
}
func (s *StoreRedis) GetPromotionCode(codeHash string) (*PromotionCode, error) {
c := &PromotionCode{}
err := s.Redis.WithConn(func(conn *goredis.Conn) error {
data, err := s.get(conn, promotionCodeKey(string(s.AppID), codeHash))
if err != nil {
return err
}
c, err = s.unmarshalPromotionCode(data)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, err
}
return c, nil
}
func (s *StoreRedis) CreatePromotionCode(code *PromotionCode) error {
return s.Redis.WithConn(func(conn *goredis.Conn) error {
return s.save(conn, promotionCodeKey(code.AppID, code.CodeHash), code, code.ExpireAt)
})
}
func (s *StoreRedis) DeletePromotionCode(code *PromotionCode) error {
return s.Redis.WithConn(func(conn *goredis.Conn) error {
return s.del(conn, promotionCodeKey(code.AppID, code.CodeHash))
})
}
func (s *StoreRedis) get(conn *goredis.Conn, key string) ([]byte, error) {
ctx := context.Background()
data, err := conn.Get(ctx, key).Bytes()
if errors.Is(err, goredis.Nil) {
return nil, ErrPromotionCodeNotFound
} else if err != nil {
return nil, err
}
return data, nil
}
func (s *StoreRedis) save(conn *goredis.Conn, key string, value interface{}, expireAt time.Time) error {
ctx := context.Background()
data, err := json.Marshal(value)
if err != nil {
return err
}
ttl := expireAt.Sub(s.Clock.NowUTC())
_, err = conn.SetNX(ctx, key, data, ttl).Result()
if errors.Is(err, goredis.Nil) {
return errors.New("promotion code already exist")
} else if err != nil {
return err
}
return nil
}
func (s *StoreRedis) del(conn *goredis.Conn, key string) error {
ctx := context.Background()
_, err := conn.Del(ctx, key).Result()
return err
}
func (s *StoreRedis) unmarshalPromotionCode(data []byte) (*PromotionCode, error) {
c := PromotionCode{}
err := json.Unmarshal(data, &c)
if err != nil {
return nil, err
}
return &c, nil
}
func promotionCodeKey(appID string, tokenHash string) string {
return fmt.Sprintf("app:%s:promotion-code:%s", appID, tokenHash)
}