Skip to content
Snippets Groups Projects
Select Git revision
  • fd8b9b2062a8d904462093ad4331915687e81eab
  • main default protected
  • v1.298.0
  • v1.297.0
  • v1.296.0
  • v1.295.0
  • v1.294.0
  • v1.293.0
  • v1.292.0
  • v1.291.0
  • v1.290.0
  • v1.289.0
  • v1.288.0
  • v1.287.0
  • v1.286.0
  • v1.285.0
  • v1.284.0
  • v1.283.0
  • v1.282.0
  • v1.281.0
  • v1.280.0
  • v1.279.0
22 results

redis.go

Blame
  • redis.go 5.14 KiB
    package redis
    
    import (
    	"context"
    	"encoding/json"
    	"os"
    	"reflect"
    	"time"
    
    	"github.com/go-redis/redis/v8"
    	"gitlab.com/uafrica/go-utils/errors"
    	"gitlab.com/uafrica/go-utils/logger"
    	"gitlab.com/uafrica/go-utils/string_utils"
    )
    
    type IRedis interface {
    	string_utils.KeyReader
    	Del(key string) error
    	SetJSON(key string, value interface{}) error
    	SetJSONIndefinitely(key string, value interface{}) error
    	SetJSONForDur(key string, value interface{}, dur time.Duration) error
    	GetJSON(key string, valueType reflect.Type) (value interface{}, ok bool)
    	SetString(key string, value string) error
    	SetStringIndefinitely(key string, value string) error
    	SetStringForDur(key string, value string, dur time.Duration) error
    }
    
    type redisWithContext struct {
    	context.Context
    	client *redis.Client
    }
    
    func New(ctx context.Context) (IRedis, error) {
    	if globalClient == nil {
    		var err error
    		if globalClient, err = connect(); err != nil {
    			return redisWithContext{Context: ctx}, errors.Wrapf(err, "cannot connect to REDIS")
    		}
    	}
    	return redisWithContext{
    		Context: ctx,
    		client:  globalClient,
    	}, nil
    }
    
    func (r redisWithContext) Del(key string) error {
    	if r.client == nil {
    		return errors.Errorf("REDIS disabled: cannot del key(%s)", key)
    	}
    	_, err := r.client.Del(r.Context, key).Result()
    	if err != nil {
    		return errors.Wrapf(err, "failed to del key(%s)", key)
    	}
    	logger.Debugf("REDIS.Del(%s)", key)
    	return nil
    }
    
    //set JSON value for 24h
    func (r redisWithContext) SetJSON(key string, value interface{}) error {
    	return r.SetJSONForDur(key, value, 24*time.Hour)
    }
    
    func (r redisWithContext) SetJSONIndefinitely(key string, value interface{}) error {
    	return r.SetJSONForDur(key, value, 0)
    }
    
    func (r redisWithContext) SetJSONForDur(key string, value interface{}, dur time.Duration) error {
    	if r.client == nil {
    		return errors.Errorf("REDIS disabled: cannot set JSON key(%s) = (%T)%v", key, value, value)
    	}