2024-08-16 22:28:05 +02:00
|
|
|
using System.Text.Json;
|
2024-08-19 16:12:28 +02:00
|
|
|
using Remora.Discord.API;
|
|
|
|
|
using Remora.Discord.API.Abstractions.Objects;
|
|
|
|
|
using Remora.Discord.API.Objects;
|
|
|
|
|
using Remora.Rest.Json;
|
2024-08-16 22:28:05 +02:00
|
|
|
using StackExchange.Redis;
|
|
|
|
|
|
|
|
|
|
namespace Catalogger.Backend.Database.Redis;
|
|
|
|
|
|
|
|
|
|
public class RedisService(Config config)
|
|
|
|
|
{
|
|
|
|
|
private readonly ConnectionMultiplexer _multiplexer = ConnectionMultiplexer.Connect(config.Database.Redis!);
|
|
|
|
|
|
2024-08-19 16:12:28 +02:00
|
|
|
private readonly JsonSerializerOptions _options = new()
|
|
|
|
|
{
|
|
|
|
|
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower
|
|
|
|
|
};
|
|
|
|
|
|
2024-08-16 22:28:05 +02:00
|
|
|
public IDatabase GetDatabase(int db = -1) => _multiplexer.GetDatabase(db);
|
|
|
|
|
|
|
|
|
|
public async Task SetAsync<T>(string key, T value, TimeSpan? expiry = null)
|
|
|
|
|
{
|
2024-08-19 16:12:28 +02:00
|
|
|
var json = JsonSerializer.Serialize(value, _options);
|
2024-08-16 22:28:05 +02:00
|
|
|
await GetDatabase().StringSetAsync(key, json, expiry);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<T?> GetAsync<T>(string key)
|
|
|
|
|
{
|
|
|
|
|
var value = await GetDatabase().StringGetAsync(key);
|
2024-08-19 16:12:28 +02:00
|
|
|
return value.IsNull ? default : JsonSerializer.Deserialize<T>(value!, _options);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task SetHashAsync<T>(string hashKey, string fieldKey, T value)
|
|
|
|
|
{
|
|
|
|
|
var json = JsonSerializer.Serialize(value, _options);
|
|
|
|
|
await GetDatabase().HashSetAsync(hashKey, fieldKey, json);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task SetHashAsync<T>(string hashKey, IEnumerable<T> values, Func<T, string> keySelector)
|
|
|
|
|
{
|
|
|
|
|
var hashEntries = values
|
|
|
|
|
.Select(v => new { Key = keySelector(v), Value = JsonSerializer.Serialize(v, _options) })
|
|
|
|
|
.Select(v => new HashEntry(v.Key, v.Value));
|
|
|
|
|
await GetDatabase().HashSetAsync(hashKey, hashEntries.ToArray());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<T?> GetHashAsync<T>(string hashKey, string fieldKey)
|
|
|
|
|
{
|
|
|
|
|
var value = await GetDatabase().HashGetAsync(hashKey, fieldKey);
|
|
|
|
|
return value.IsNull ? default : JsonSerializer.Deserialize<T>(value!, _options);
|
2024-08-16 22:28:05 +02:00
|
|
|
}
|
|
|
|
|
}
|