Select Git revision
OrderCreateWebhook.php
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)
}