using StackExchange.Redis;
using System.Text.Json;
using Telegrator.Core.States;
namespace Telegrator.States;
///
/// Provides a Redis-based implementation of the interface.
/// Serializes state objects to JSON format before storing them in the Redis database.
///
public class RedisStateStorage(IConnectionMultiplexer redis) : IStateStorage
{
private readonly IDatabase _db = redis.GetDatabase();
///
public async Task SetAsync(string key, T state, CancellationToken cancellationToken)
{
string json = JsonSerializer.Serialize(state);
await _db.StringSetAsync(key, json);
}
///
public async Task GetAsync(string key, CancellationToken cancellationToken)
{
RedisValue json = await _db.StringGetAsync(key);
string? jsonStr = json;
if (jsonStr is null)
return default;
return JsonSerializer.Deserialize(json: jsonStr);
}
///
public async Task DeleteAsync(string key, CancellationToken cancellationToken = default)
{
await _db.KeyDeleteAsync(key);
}
}