1
|
|
|
package user |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"context" |
5
|
|
|
|
6
|
|
|
"github.com/dgraph-io/ristretto" |
7
|
|
|
"github.com/memnix/memnix-rest/domain" |
8
|
|
|
"github.com/memnix/memnix-rest/infrastructures" |
9
|
|
|
"github.com/memnix/memnix-rest/pkg/utils" |
10
|
|
|
"github.com/pkg/errors" |
11
|
|
|
) |
12
|
|
|
|
13
|
|
|
type RistrettoRepository struct { |
14
|
|
|
RistrettoCache *ristretto.Cache // RistrettoCache is the cache |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
func NewRistrettoCache(ristrettoCache *ristretto.Cache) IRistrettoRepository { |
18
|
|
|
return &RistrettoRepository{ |
19
|
|
|
RistrettoCache: ristrettoCache, |
20
|
|
|
} |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
func (r *RistrettoRepository) Get(ctx context.Context, id uint) (domain.User, error) { |
24
|
|
|
_, span := infrastructures.GetFiberTracer().Start(ctx, "GetByIDRistretto") |
25
|
|
|
defer span.End() |
26
|
|
|
|
27
|
|
|
ristrettoHit, ok := r.RistrettoCache.Get("user:" + utils.ConvertUIntToStr(id)) |
28
|
|
|
if !ok { |
29
|
|
|
return domain.User{}, errors.New("user not found") |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
switch ristrettoHit.(type) { |
33
|
|
|
case domain.User: |
34
|
|
|
return ristrettoHit.(domain.User), nil |
35
|
|
|
default: |
36
|
|
|
return domain.User{}, errors.New("user not found") |
37
|
|
|
} |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
func (r *RistrettoRepository) Set(ctx context.Context, user domain.User) error { |
41
|
|
|
_, span := infrastructures.GetFiberTracer().Start(ctx, "SetByIDRistretto") |
42
|
|
|
defer span.End() |
43
|
|
|
|
44
|
|
|
r.RistrettoCache.Set("user:"+utils.ConvertUIntToStr(user.ID), user, 0) |
45
|
|
|
|
46
|
|
|
r.RistrettoCache.Wait() |
47
|
|
|
|
48
|
|
|
return nil |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
func (r *RistrettoRepository) Delete(ctx context.Context, id uint) error { |
52
|
|
|
_, span := infrastructures.GetFiberTracer().Start(ctx, "DeleteByIDRistretto") |
53
|
|
|
defer span.End() |
54
|
|
|
|
55
|
|
|
r.RistrettoCache.Del("user:" + utils.ConvertUIntToStr(id)) |
56
|
|
|
|
57
|
|
|
return nil |
58
|
|
|
} |
59
|
|
|
|