-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransform.go
More file actions
92 lines (83 loc) · 2.22 KB
/
transform.go
File metadata and controls
92 lines (83 loc) · 2.22 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package cachex
import (
"context"
"encoding/json"
"github.com/pkg/errors"
)
// transformCache wraps a Cache[A] and provides type transformation to Cache[B]
type transformCache[A, B any] struct {
cache Cache[A]
encode func(B) (A, error)
decode func(A) (B, error)
}
// Transform creates a new TransformCache with custom encode/decode functions
func Transform[A, B any](
cache Cache[A],
encode func(B) (A, error),
decode func(A) (B, error),
) Cache[B] {
return &transformCache[A, B]{
cache: cache,
encode: encode,
decode: decode,
}
}
// Set encodes the value and stores it in the underlying cache
func (t *transformCache[A, B]) Set(ctx context.Context, key string, value B) error {
encoded, err := t.encode(value)
if err != nil {
return errors.Wrap(err, "failed to encode value")
}
return t.cache.Set(ctx, key, encoded)
}
// Get retrieves the value from the underlying cache and decodes it
func (t *transformCache[A, B]) Get(ctx context.Context, key string) (B, error) {
var zero B
encoded, err := t.cache.Get(ctx, key)
if err != nil {
return zero, err
}
decoded, err := t.decode(encoded)
if err != nil {
return zero, errors.Wrap(err, "failed to decode value")
}
return decoded, nil
}
// Del removes the value from the underlying cache
func (t *transformCache[A, B]) Del(ctx context.Context, key string) error {
return t.cache.Del(ctx, key)
}
// JSONTransform creates a TransformCache that uses JSON encoding/decoding
// to convert between Cache[[]byte] and Cache[T]
func JSONTransform[T any](cache Cache[[]byte]) Cache[T] {
return Transform(
cache,
func(value T) ([]byte, error) {
return json.Marshal(value)
},
func(data []byte) (T, error) {
var value T
err := json.Unmarshal(data, &value)
return value, err
},
)
}
// StringJSONTransform creates a TransformCache that uses JSON encoding/decoding
// to convert between Cache[string] and Cache[T]
func StringJSONTransform[T any](cache Cache[string]) Cache[T] {
return Transform(
cache,
func(value T) (string, error) {
data, err := json.Marshal(value)
if err != nil {
return "", err
}
return string(data), nil
},
func(data string) (T, error) {
var value T
err := json.Unmarshal([]byte(data), &value)
return value, err
},
)
}