-
Notifications
You must be signed in to change notification settings - Fork 13
/
client.go
69 lines (56 loc) · 1.44 KB
/
client.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
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package auth
import (
"context"
"github.com/MainfluxLabs/mainflux"
"github.com/go-redis/redis/v8"
)
// Client represents Auth cache.
type Client interface {
Identify(ctx context.Context, thingKey string) (string, error)
GetConnByKey(ctx context.Context, thingKey string) (mainflux.ConnByKeyRes, error)
}
const (
chanPrefix = "channel"
keyPrefix = "thing_key"
)
type client struct {
redisClient *redis.Client
things mainflux.ThingsServiceClient
}
// New returns redis channel cache implementation.
func New(redisClient *redis.Client, things mainflux.ThingsServiceClient) Client {
return client{
redisClient: redisClient,
things: things,
}
}
func (c client) Identify(ctx context.Context, thingKey string) (string, error) {
tkey := keyPrefix + ":" + thingKey
thingID, err := c.redisClient.Get(ctx, tkey).Result()
if err != nil {
t := &mainflux.Token{
Value: string(thingKey),
}
thid, err := c.things.Identify(context.TODO(), t)
if err != nil {
return "", err
}
return thid.GetValue(), nil
}
return thingID, nil
}
func (c client) GetConnByKey(ctx context.Context, thingKey string) (mainflux.ConnByKeyRes, error) {
req := &mainflux.ConnByKeyReq{
Key: thingKey,
}
conn, err := c.things.GetConnByKey(ctx, req)
if err != nil {
return mainflux.ConnByKeyRes{}, err
}
if conn != nil {
return *conn, nil
}
return mainflux.ConnByKeyRes{}, nil
}