-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.go
67 lines (54 loc) · 1.28 KB
/
hash.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
package ioredis
import (
"encoding/json"
"fmt"
"time"
"github.com/tinh-tinh/ioredis/common"
)
type Hash[M any] struct {
Name string
redis common.Redis
}
func NewHash[M any](name string, r common.Redis) *Hash[M] {
return &Hash[M]{
Name: name,
redis: r,
}
}
func (h *Hash[M]) Expire(time time.Duration) *Hash[M] {
result := h.redis.GetClient().Expire(h.redis.GetCtx(), h.Name, time)
fmt.Println(result)
return h
}
func (h *Hash[M]) Upsert(key string, data *M) error {
val, err := json.Marshal(data)
if err != nil {
return err
}
return h.redis.GetClient().HSet(h.redis.GetCtx(), h.Name, key, string(val)).Err()
}
func (h *Hash[M]) FindMany() ([]*M, error) {
var data []*M
mapper, err := h.redis.GetClient().HGetAll(h.redis.GetCtx(), h.Name).Result()
if err != nil {
return nil, err
}
for _, v := range mapper {
var item *M
json.Unmarshal([]byte(v), &item)
data = append(data, item)
}
return data, nil
}
func (h *Hash[M]) FindByKey(key string) (*M, error) {
var data M
val, err := h.redis.GetClient().HGet(h.redis.GetCtx(), h.Name, key).Result()
if err != nil {
return nil, err
}
json.Unmarshal([]byte(val), &data)
return &data, nil
}
func (h *Hash[M]) Delete(key string) error {
return h.redis.GetClient().HDel(h.redis.GetCtx(), h.Name, key).Err()
}