-
Notifications
You must be signed in to change notification settings - Fork 7
/
cache.go
99 lines (78 loc) · 1.85 KB
/
cache.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
package cacheDB
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/colibri-project-io/colibri-sdk-go/pkg/base/config"
)
// Cache struct
type Cache[T any] struct {
name string
ttl time.Duration
}
// NewCache create a new pointer to Cache struct.
func NewCache[T any](name string, ttl time.Duration) *Cache[T] {
return &Cache[T]{name, ttl}
}
// Many returns a slice of T value
func (c *Cache[T]) Many(ctx context.Context) ([]T, error) {
if err := c.validate(); err != nil {
return nil, err
}
result, err := instance.Get(ctx, c.getNamePrefixed()).Bytes()
if err != nil {
return nil, err
}
list := make([]T, 0)
if err = json.Unmarshal(result, &list); err != nil {
return nil, err
}
return list, nil
}
// One return a pointer of T value
func (c *Cache[T]) One(ctx context.Context) (*T, error) {
if err := c.validate(); err != nil {
return nil, err
}
result, err := instance.Get(ctx, c.getNamePrefixed()).Bytes()
if err != nil {
return nil, err
}
model := new(T)
if err = json.Unmarshal(result, &model); err != nil {
return nil, err
}
return model, nil
}
// Set save data in cacheDB
func (c *Cache[T]) Set(ctx context.Context, data any) error {
if err := c.validate(); err != nil {
return err
}
jsonData, err := json.Marshal(data)
if err != nil {
return err
}
return instance.Set(ctx, c.getNamePrefixed(), jsonData, c.ttl).Err()
}
// Del delete data in cachedDB
func (c *Cache[T]) Del(ctx context.Context) error {
if err := c.validate(); err != nil {
return err
}
return instance.Del(ctx, c.getNamePrefixed()).Err()
}
func (c *Cache[T]) validate() error {
if instance == nil {
return errors.New("Cache not initialized")
}
if c.name == "" {
return errors.New("Cache without name")
}
return nil
}
func (c *Cache[T]) getNamePrefixed() string {
return fmt.Sprintf("%s::%s", config.APP_NAME, c.name)
}