2024-11-29 16:25:20 +01:00

43 lines
1.8 KiB
C#

using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EnvelopeGenerator.Application.Extensions
{
public static class CacheExtensions
{
public static Task SetLongAsync(this IDistributedCache cache, string key, long value, DistributedCacheEntryOptions? options = null)
=> options is null
? cache.SetAsync(key, BitConverter.GetBytes(value))
: cache.SetAsync(key, BitConverter.GetBytes(value), options: options);
public static async Task<long?> GetLongAsync(this IDistributedCache cache, string key)
{
var value = await cache.GetAsync(key);
return value is null ? null : BitConverter.ToInt64(value, 0);
}
public static Task SetDateTimeAsync(this IDistributedCache cache, string key, DateTime value, DistributedCacheEntryOptions? options = null)
=> cache.SetLongAsync(key: key, value: value.Ticks, options: options);
public static async Task<DateTime?> GetDateTimeAsync(this IDistributedCache cache, string key)
{
var value = await cache.GetAsync(key);
return value is null ? null : new(BitConverter.ToInt64(value, 0));
}
public static Task SetTimeSpanAsync(this IDistributedCache cache, string key, TimeSpan value, DistributedCacheEntryOptions? options = null)
=> cache.SetLongAsync(key: key, value: value.Ticks, options: options);
public static async Task<TimeSpan?> GetTimeSpanAsync(this IDistributedCache cache, string key)
{
var value = await cache.GetAsync(key);
return value is null ? null : new(BitConverter.ToInt64(value, 0));
}
}
}