-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathredis.go
71 lines (62 loc) · 1.64 KB
/
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
package phada
import (
"context"
"encoding/json"
"errors"
"time"
redis "github.com/redis/go-redis/v9"
)
// RedisSessionStore
type RedisSessionStore struct {
SessionStore
lastWriteTime time.Time
client *redis.Client
}
// NewRedisSessionStore
//
// Creates an inmemory store that uses a concurrent map to store sessions
func NewRedisSessionStore(redisClient *redis.Client) *RedisSessionStore {
return &RedisSessionStore{
lastWriteTime: time.Now(),
client: redisClient,
}
}
// PutHop
func (m *RedisSessionStore) PutHop(ussdRequest *UssdRequestSession) error {
ctx := context.Background()
data, err := m.client.Get(ctx, ussdRequest.SessionID).Result()
if err != nil {
return m.client.Set(ctx, ussdRequest.SessionID, ussdRequest.ToJSON(), 0).Err()
}
if data == "" {
return m.client.Set(ctx, ussdRequest.SessionID, ussdRequest.ToJSON(), 0).Err()
}
var existing *UssdRequestSession
err = json.Unmarshal([]byte(data), existing)
if err != nil {
return err
}
existing.RecordHop(ussdRequest.Text)
err = m.client.Set(ctx, ussdRequest.SessionID, existing.ToJSON(), 0).Err()
if err != nil {
m.lastWriteTime = time.Now()
}
return err
}
// Delete
func (m *RedisSessionStore) Delete(sessionID string) {
m.client.Del(context.Background(), sessionID)
}
// Get
func (m *RedisSessionStore) Get(sessionID string) (*UssdRequestSession, error) {
data, err := m.client.Get(context.Background(), sessionID).Result()
if err != nil {
return nil, errors.New("Session does not exist in SessionStore")
}
var existing *UssdRequestSession
err = json.Unmarshal([]byte(data), existing)
if err != nil {
return nil, err
}
return existing, nil
}