void.cat/VoidCat/Services/InMemory/InMemoryCache.cs

72 lines
1.8 KiB
C#
Raw Normal View History

2022-02-21 22:35:06 +00:00
using Microsoft.Extensions.Caching.Memory;
2022-06-13 13:35:26 +00:00
using Newtonsoft.Json;
2022-02-21 22:35:06 +00:00
using VoidCat.Services.Abstractions;
namespace VoidCat.Services.InMemory;
2022-06-13 13:35:26 +00:00
/// <inheritdoc />
2022-02-21 22:35:06 +00:00
public class InMemoryCache : ICache
{
private readonly IMemoryCache _cache;
public InMemoryCache(IMemoryCache cache)
{
_cache = cache;
}
2022-06-13 13:35:26 +00:00
/// <inheritdoc />
2022-02-21 22:35:06 +00:00
public ValueTask<T?> Get<T>(string key)
{
2022-06-13 13:35:26 +00:00
var json = _cache.Get<string>(key);
if (string.IsNullOrEmpty(json)) return default;
return ValueTask.FromResult(JsonConvert.DeserializeObject<T?>(json));
2022-02-21 22:35:06 +00:00
}
2022-05-19 22:27:49 +00:00
2022-06-13 13:35:26 +00:00
/// <inheritdoc />
2022-02-21 22:35:06 +00:00
public ValueTask Set<T>(string key, T value, TimeSpan? expire = null)
{
2022-06-13 13:35:26 +00:00
var json = JsonConvert.SerializeObject(value);
2022-02-21 22:35:06 +00:00
if (expire.HasValue)
{
2022-06-13 13:35:26 +00:00
_cache.Set(key, json, expire.Value);
2022-02-21 22:35:06 +00:00
}
else
{
2022-06-13 13:35:26 +00:00
_cache.Set(key, json);
2022-02-21 22:35:06 +00:00
}
return ValueTask.CompletedTask;
}
2022-05-19 22:27:49 +00:00
2022-06-13 13:35:26 +00:00
/// <inheritdoc />
2022-02-21 22:35:06 +00:00
public ValueTask<string[]> GetList(string key)
{
2022-05-19 22:27:49 +00:00
return ValueTask.FromResult(_cache.Get<string[]>(key) ?? Array.Empty<string>());
2022-02-21 22:35:06 +00:00
}
2022-05-19 22:27:49 +00:00
2022-06-13 13:35:26 +00:00
/// <inheritdoc />
2022-02-21 22:35:06 +00:00
public ValueTask AddToList(string key, string value)
{
var list = new HashSet<string>(GetList(key).Result);
list.Add(value);
_cache.Set(key, list.ToArray());
return ValueTask.CompletedTask;
}
2022-06-13 13:35:26 +00:00
/// <inheritdoc />
public ValueTask RemoveFromList(string key, string value)
{
var list = new HashSet<string>(GetList(key).Result);
list.Remove(value);
_cache.Set(key, list.ToArray());
return ValueTask.CompletedTask;
}
2022-06-13 13:35:26 +00:00
/// <inheritdoc />
public ValueTask Delete(string key)
{
_cache.Remove(key);
2022-05-19 22:27:49 +00:00
return ValueTask.CompletedTask;
}
2022-05-19 22:27:49 +00:00
}