qtc-net-server/qtc-net-server/Extensions/DistributedCacheExtensions.cs
2025-11-14 17:03:43 -08:00

52 lines
1.6 KiB
C#

using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;
namespace qtc_api.Extensions
{
public static class DistributedCacheExtensions
{
public static async Task SetRecordAsync<T> (this IDistributedCache cache, string recordId, T data, TimeSpan? absoluteExpireTime = null)
{
var options = new DistributedCacheEntryOptions();
options.AbsoluteExpirationRelativeToNow = absoluteExpireTime ?? TimeSpan.FromSeconds(15);
var jsonData = JsonSerializer.Serialize(data);
await cache.SetStringAsync(recordId, jsonData, options);
}
public static async Task SetImageAsync(this IDistributedCache cache, string recordId, byte[] data, TimeSpan? absoluteExpireTime = null)
{
var options = new DistributedCacheEntryOptions();
options.AbsoluteExpirationRelativeToNow = absoluteExpireTime ?? TimeSpan.FromMinutes(30);
await cache.SetAsync(recordId, data, options);
}
public static async Task<T?> GetRecordAsync<T>(this IDistributedCache cache, string recordId)
{
var jsonData = await cache.GetStringAsync(recordId);
if(jsonData == null)
{
return default;
}
return JsonSerializer.Deserialize<T>(jsonData);
}
public static async Task<byte[]?> GetImageAsync(this IDistributedCache cache, string recordId)
{
var bytes = await cache.GetAsync(recordId);
if (bytes == null)
{
return default;
}
return bytes;
}
}
}