tagger/internal/data/redis.go

64 lines
1.8 KiB
Go
Raw Normal View History

2024-04-04 20:37:54 +00:00
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. All rights reserved.
2024-04-04 20:30:41 +00:00
package data
import (
"context"
"github.com/redis/go-redis/v9"
)
type RedisClientConnector interface {
Ping(ctx context.Context) *redis.StatusCmd
LRange(ctx context.Context, key string, start, stop int64) *redis.StringSliceCmd
SInter(ctx context.Context, keys ...string) *redis.StringSliceCmd
Keys(ctx context.Context, pattern string) *redis.StringSliceCmd
SAdd(ctx context.Context, key string, members ...interface{}) *redis.IntCmd
SIsMember(ctx context.Context, key string, member interface{}) *redis.BoolCmd
}
type Redis struct {
client RedisClientConnector
}
func NewRedisConnector(client RedisClientConnector) *Redis {
if client == nil {
client = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
}
return &Redis{ client: client }
}
func (r *Redis) Tags(context context.Context) []string {
result,_ := r.client.Keys(context, "*").Result()
return result
}
func (r *Redis) Connected(context context.Context) bool {
if e := r.client.Ping(context).Err(); e != nil {
return false
}
return true
}
func (r *Redis) Query(context context.Context, terms []string) ([]string, error) {
result,_ := r.client.SInter(context, terms...).Result()
return result, nil
}
func (r *Redis) AddTag(context context.Context, key string, resource string) error {
if r,e := r.client.SAdd(context, key, resource).Result(); r != 1 || e != nil {
return e
}
return nil
}
func (r *Redis) ResourceHasTag(context context.Context, resource string, tag string) bool {
if r,e := r.client.SIsMember(context, tag, resource).Result(); r == false || e != nil {
return false
}
return true
}