-
Notifications
You must be signed in to change notification settings - Fork 15
/
things.go
72 lines (59 loc) · 1.74 KB
/
things.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
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package redis
import (
"context"
"fmt"
"github.com/MainfluxLabs/mainflux/pkg/errors"
"github.com/MainfluxLabs/mainflux/things"
"github.com/go-redis/redis/v8"
)
const (
keyPrefix = "thing_key"
idPrefix = "thing"
)
var _ things.ThingCache = (*thingCache)(nil)
type thingCache struct {
client *redis.Client
}
// NewThingCache returns redis thing cache implementation.
func NewThingCache(client *redis.Client) things.ThingCache {
return &thingCache{
client: client,
}
}
func (tc *thingCache) Save(ctx context.Context, thingKey string, thingID string) error {
tkey := fmt.Sprintf("%s:%s", keyPrefix, thingKey)
if err := tc.client.Set(ctx, tkey, thingID, 0).Err(); err != nil {
return errors.Wrap(errors.ErrCreateEntity, err)
}
tid := fmt.Sprintf("%s:%s", idPrefix, thingID)
if err := tc.client.Set(ctx, tid, thingKey, 0).Err(); err != nil {
return errors.Wrap(errors.ErrCreateEntity, err)
}
return nil
}
func (tc *thingCache) ID(ctx context.Context, thingKey string) (string, error) {
tkey := fmt.Sprintf("%s:%s", keyPrefix, thingKey)
thingID, err := tc.client.Get(ctx, tkey).Result()
if err != nil {
return "", errors.Wrap(errors.ErrNotFound, err)
}
return thingID, nil
}
func (tc *thingCache) Remove(ctx context.Context, thingID string) error {
tid := fmt.Sprintf("%s:%s", idPrefix, thingID)
key, err := tc.client.Get(ctx, tid).Result()
// Redis returns Nil Reply when key does not exist.
if err == redis.Nil {
return nil
}
if err != nil {
return errors.Wrap(errors.ErrRemoveEntity, err)
}
tkey := fmt.Sprintf("%s:%s", keyPrefix, key)
if err := tc.client.Del(ctx, tkey, tid).Err(); err != nil {
return errors.Wrap(errors.ErrRemoveEntity, err)
}
return nil
}