using skydiveLogs_api.Domain;
using skydiveLogs_api.DomainBusiness.Interfaces;
using System;
using System.Runtime.Caching;
namespace skydiveLogs_api.DomainBusiness
{
public class CacheService : ICacheService
{
#region Public Constructors
public CacheService()
{
_memoryCache = MemoryCache.Default;
}
#endregion Public Constructors
#region Private Fields
private readonly MemoryCache _memoryCache;
#endregion Private Fields
#region Public Methods
///
/// Checks if a specific cache entry exists for a given type and user ID.
///
/// The type of data to check for in the cache.
/// Optional user ID to distinguish cache entries. Default is 0.
/// True if the cache entry exists and is valid, otherwise false.
public bool Contains(CacheType type, int userId = 0)
{
var key = GetKey(userId, type);
return _memoryCache.Contains(key.ToString());
}
///
/// Removes a cache entry from the store.
///
/// The type of data to remove from the cache.
/// Optional user ID to identify the cache entry. Default is 0.
public void Delete(CacheType type, int userId = 0)
{
var key = GetKey(userId, type);
_memoryCache.Remove(key.ToString());
}
///
/// Retrieves data from the cache for a specified type and user ID.
///
/// The expected type of the cached data.
/// The type of data to retrieve from the cache.
/// Optional user ID to identify the cache entry. Default is 0.
/// The cached data cast to type T, or default(T) if not found or expired.
public T Get(CacheType type, int userId = 0)
{
var key = GetKey(userId, type);
return (T)_memoryCache.Get(key.ToString());
}
///
/// Stores data in the cache with a specified expiry time.
///
/// The unique identifier for the cache key.
/// The object data to be cached.
/// The duration in milliseconds before the cache entry expires.
/// Optional user ID to distinguish cache entries. Default is 0.
/// Thrown when duration is less than or equal to zero.
public void Put(CacheType type, object value, int duration, int userId = 0)
{
var key = GetKey(userId, type);
if (duration <= 0)
throw new ArgumentException("Duration cannot be less or equal to zero", "duration");
var policy = new CacheItemPolicy
{
AbsoluteExpiration = DateTime.Now.AddMilliseconds(duration)
};
_memoryCache.Set(key.ToString(), value, policy);
}
///
/// Generates a cache key by combining the user ID and cache type.
///
/// The user ID to include in the key.
/// The cache type to include in the key.
/// A concatenated string key combining userId and type.
private string GetKey(int userId, CacheType type)
{
return $"{userId}-{type}";
}
#endregion Public Methods
}
}