diff --git a/src/CascadeRepos/RedisHashRepository.cs b/src/CascadeRepos/RedisHashRepository.cs index dfc1d6d..69dfbb1 100644 --- a/src/CascadeRepos/RedisHashRepository.cs +++ b/src/CascadeRepos/RedisHashRepository.cs @@ -96,6 +96,8 @@ protected override async Task CoreSet(TK key, T item, CancellationToken cancella { await _database.HashSetAsync(_redisKeyAdapter()!.ToString(), KeyToKeyAdapter(key)!.ToString(), JsonConvert.SerializeObject(item)); + + await SetExpiration(); } /// @@ -104,6 +106,8 @@ protected override async Task CoreSetAll(IList items, CancellationToken cance foreach (var item in items) await _database.HashSetAsync(GetSetAllKey, ObjectToKeyAdapter(item)!.ToString(), JsonConvert.SerializeObject(item)); + + await SetExpiration(); } /// @@ -121,4 +125,12 @@ protected override async Task CoreDelete(TK key, CancellationToken cancellationT { await _database.HashDeleteAsync(_redisKeyAdapter()!.ToString(), KeyToKeyAdapter(key)!.ToString()); } + + private async Task SetExpiration() + { + var expirationTime = CalculateExpirationTime(); + + if (expirationTime != null) + await _database.KeyExpireAsync(_redisKeyAdapter()!.ToString(), expirationTime.Value.DateTime); + } } \ No newline at end of file diff --git a/tests/CascadeRepos.UnitTests/RedisHashRepositoryTests.cs b/tests/CascadeRepos.UnitTests/RedisHashRepositoryTests.cs index b4f1db0..3c0dc2e 100644 --- a/tests/CascadeRepos.UnitTests/RedisHashRepositoryTests.cs +++ b/tests/CascadeRepos.UnitTests/RedisHashRepositoryTests.cs @@ -178,7 +178,6 @@ public async Task GetAll_Adds_Items_Using_CoreSetAll() _databaseMock.Verify(x => x.HashGetAllAsync(It.IsAny(), CommandFlags.None), Times.Once); } - [Fact] public async Task GetList_Returns_ListOfItems() { @@ -255,7 +254,6 @@ public async Task GetList_Adds_Items_Using_CoreSetList() _databaseMock.Verify(x => x.HashGetAllAsync(It.IsAny(), CommandFlags.None), Times.Once); } - [Fact] public async Task Throws_When_ObjectToKey_Is_Not_Defined() { @@ -285,4 +283,28 @@ public async Task Throws_When_ObjectToKey_Is_Not_Defined() await Assert.ThrowsAsync(async () => await _repository.GetList(listId, true, CancellationToken.None)); } + + [Fact] + public async Task CoreSet_Sets_Hash_And_Expires_Key() + { + // Arrange + var key = "cacheKey"; + var value = new SomeObject + { + Id = key, + Name = "Some Name" + }; + + // Act + _repository.SetTimeToLive(TimeSpan.FromSeconds(2)); + await _repository.Set(key, value); + + // Assert + _databaseMock.Verify( + d => d.HashSetAsync(It.IsAny(), It.IsAny(),It.IsAny(), It.IsAny(), + It.IsAny()), Times.Once); + _databaseMock.Verify( + d => d.KeyExpireAsync(It.IsAny(), It.IsAny(), It.IsAny()), + Times.Once); + } } \ No newline at end of file