2018-09-04 22:19:43 +02:00
|
|
|
//
|
2019-07-18 15:01:09 +02:00
|
|
|
// Copyright (c) 2019
|
2018-09-04 22:19:43 +02:00
|
|
|
// Mainflux
|
|
|
|
//
|
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
//
|
|
|
|
|
|
|
|
package redis
|
|
|
|
|
|
|
|
import (
|
2019-07-18 15:01:09 +02:00
|
|
|
"context"
|
2018-09-04 22:19:43 +02:00
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/go-redis/redis"
|
|
|
|
"github.com/mainflux/mainflux/things"
|
|
|
|
)
|
|
|
|
|
|
|
|
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,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-07-18 15:01:09 +02:00
|
|
|
func (tc *thingCache) Save(_ context.Context, thingKey string, thingID string) error {
|
2018-09-04 22:19:43 +02:00
|
|
|
tkey := fmt.Sprintf("%s:%s", keyPrefix, thingKey)
|
2018-12-05 13:09:25 +01:00
|
|
|
if err := tc.client.Set(tkey, thingID, 0).Err(); err != nil {
|
2018-09-04 22:19:43 +02:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2018-12-05 13:09:25 +01:00
|
|
|
tid := fmt.Sprintf("%s:%s", idPrefix, thingID)
|
2018-09-04 22:19:43 +02:00
|
|
|
return tc.client.Set(tid, thingKey, 0).Err()
|
|
|
|
}
|
|
|
|
|
2019-07-18 15:01:09 +02:00
|
|
|
func (tc *thingCache) ID(_ context.Context, thingKey string) (string, error) {
|
2018-09-04 22:19:43 +02:00
|
|
|
tkey := fmt.Sprintf("%s:%s", keyPrefix, thingKey)
|
|
|
|
thingID, err := tc.client.Get(tkey).Result()
|
|
|
|
if err != nil {
|
2018-12-05 13:09:25 +01:00
|
|
|
return "", err
|
2018-09-04 22:19:43 +02:00
|
|
|
}
|
|
|
|
|
2018-12-05 13:09:25 +01:00
|
|
|
return thingID, nil
|
2018-09-04 22:19:43 +02:00
|
|
|
}
|
|
|
|
|
2019-07-18 15:01:09 +02:00
|
|
|
func (tc *thingCache) Remove(_ context.Context, thingID string) error {
|
2018-12-05 13:09:25 +01:00
|
|
|
tid := fmt.Sprintf("%s:%s", idPrefix, thingID)
|
2018-09-04 22:19:43 +02:00
|
|
|
key, err := tc.client.Get(tid).Result()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
tkey := fmt.Sprintf("%s:%s", keyPrefix, key)
|
|
|
|
|
|
|
|
return tc.client.Del(tkey, tid).Err()
|
|
|
|
}
|