2024-05-29 06:08:14 +03:00
|
|
|
|
using Microsoft.Extensions.Caching.Distributed;
|
|
|
|
|
using Mirea.Api.Security.Common.Interfaces;
|
2024-05-29 06:11:29 +03:00
|
|
|
|
using System;
|
2024-05-29 06:08:14 +03:00
|
|
|
|
using System.Text.Json;
|
|
|
|
|
using System.Threading;
|
2024-05-29 06:11:29 +03:00
|
|
|
|
using System.Threading.Tasks;
|
2024-05-29 06:08:14 +03:00
|
|
|
|
|
|
|
|
|
namespace Mirea.Api.Endpoint.Common.Services.Security;
|
|
|
|
|
|
|
|
|
|
public class DistributedCacheService(IDistributedCache cache) : ICacheService
|
|
|
|
|
{
|
|
|
|
|
public async Task SetAsync<T>(string key, T value, TimeSpan? absoluteExpirationRelativeToNow = null, TimeSpan? slidingExpiration = null, CancellationToken cancellationToken = default)
|
|
|
|
|
{
|
|
|
|
|
var options = new DistributedCacheEntryOptions
|
|
|
|
|
{
|
|
|
|
|
AbsoluteExpirationRelativeToNow = absoluteExpirationRelativeToNow,
|
|
|
|
|
SlidingExpiration = slidingExpiration
|
|
|
|
|
};
|
|
|
|
|
|
2024-06-21 21:44:34 +03:00
|
|
|
|
var serializedValue = value as byte[] ?? JsonSerializer.SerializeToUtf8Bytes(value);
|
2024-05-29 06:08:14 +03:00
|
|
|
|
await cache.SetAsync(key, serializedValue, options, cancellationToken);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<T?> GetAsync<T>(string key, CancellationToken cancellationToken = default)
|
|
|
|
|
{
|
|
|
|
|
var cachedValue = await cache.GetAsync(key, cancellationToken);
|
|
|
|
|
return cachedValue == null ? default : JsonSerializer.Deserialize<T>(cachedValue);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public Task RemoveAsync(string key, CancellationToken cancellationToken = default) =>
|
|
|
|
|
cache.RemoveAsync(key, cancellationToken);
|
|
|
|
|
}
|