-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_data.go
More file actions
71 lines (61 loc) · 1.66 KB
/
cache_data.go
File metadata and controls
71 lines (61 loc) · 1.66 KB
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 response_cache
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"strings"
)
// CacheData is a struct that holds the cache data
// Key is the cache key, it is consisted of userId, methodName, and idempotencyKey
// Value is the gRPC response
// TypeName is the type of the response
// UnmarshalValue is the unmarshaled response
// MarshalValue is the marshaled response
type CacheData struct {
Key string
Value interface{}
TypeName string
UnmarshalValue interface{}
MarshalValue []byte
}
const LockValue string = "locked"
func Create(methodName string, userId string, idempotencyKey string) *CacheData {
return &CacheData{
Key: GenerateCacheKey(userId, methodName, idempotencyKey),
}
}
func GenerateCacheKey(keys ...string) string {
fmt.Printf("keys: %v\n", strings.Join(keys, ":"))
return strings.TrimSpace(strings.Join(keys, ":"))
}
// Marshal marshals the cache data
// It needs to specify the type to restore, so json.Marshal is applied twice only for the response
func (c *CacheData) Marshal() ([]byte, error) {
if c.Value == LockValue {
c.TypeName = "string"
} else {
c.TypeName = reflect.TypeOf(c.Value).Elem().Name()
}
bytes, err := json.Marshal(c.Value)
if err != nil {
return nil, err
}
c.MarshalValue = bytes
return json.Marshal(c)
}
func (c *CacheData) Unmarshal(data []byte) error {
if err := json.Unmarshal(data, c); err != nil {
return err
}
t, ok := Registry.Get(c.TypeName)
if !ok {
return errors.New("unknown type: " + c.TypeName)
}
instance := reflect.New(t).Interface()
if err := json.Unmarshal(c.MarshalValue, instance); err != nil {
return err
}
c.UnmarshalValue = instance
return nil
}