import (
"context"
"encoding/json"
"github.com/redis/go-redis/v9"
"github.com/amarnathcjd/gogram/telegram"
)
type RedisCache struct {
client *redis.Client
key string
}
func NewRedisCache(addr, password, key string) *RedisCache {
rdb := redis.NewClient(&redis.Options{
Addr: addr,
Password: password,
})
return &RedisCache{client: rdb, key: key}
}
// Read retrieves the JSON blob from Redis and unmarshals it
func (r *RedisCache) Read() (*telegram.InputPeerCache, error) {
val, err := r.client.Get(context.Background(), r.key).Result()
if err == redis.Nil {
// Cache misses are fine, return empty structure
return &telegram.InputPeerCache{
InputChannels: make(map[int64]int64),
InputUsers: make(map[int64]int64),
UsernameMap: make(map[string]int64),
}, nil
}
if err != nil {
return nil, err
}
var data telegram.InputPeerCache
if err := json.Unmarshal([]byte(val), &data); err != nil {
return nil, err
}
return &data, nil
}
// Write serializes the cache and saves it to Redis
func (r *RedisCache) Write(data *telegram.InputPeerCache) error {
bytes, err := json.Marshal(data)
if err != nil {
return err
}
return r.client.Set(context.Background(), r.key, bytes, 0).Err()
}
func (r *RedisCache) Close() error {
return r.client.Close()
}