Core.Blueprint.DAL/Core.Blueprint.DAL.Mongo/Service/MongoSampleService.cs

100 lines
3.5 KiB
C#

using Core.Blueprint.DAL.Mongo.Contracts;
using Core.Blueprint.DAL.Mongo.Entities.Collections;
using Core.Blueprint.DAL.Mongo.Entities.Requests;
using Core.Blueprint.Mongo;
using Core.Blueprint.Redis;
using Core.Blueprint.Redis.Helpers;
using Mapster;
namespace Core.Blueprint.DAL.Mongo.Service
{
public class MongoSampleService : IMongoSampleService
{
private readonly CollectionRepository<SampleCollection> repository;
private readonly ICacheSettings cacheSettings;
private readonly IRedisCacheProvider cacheProvider;
public MongoSampleService(CollectionRepository<SampleCollection> repository,
IRedisCacheProvider cacheProvider, ICacheSettings cacheSettings)
{
this.repository = repository;
this.repository.CollectionInitialization();
this.cacheSettings = cacheSettings;
this.cacheProvider = cacheProvider;
}
public async ValueTask<SampleCollection> CreateSample(SampleRequest newSample, CancellationToken cancellationToken)
{
var sampleCollection = newSample.Adapt<SampleCollection>();
await this.repository.InsertOneAsync(sampleCollection);
await ResetCollectionCache();
return sampleCollection;
}
public async ValueTask<SampleCollection> GetSampleById(string _id, CancellationToken cancellationToken)
{
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetSampleById", _id);
var cachedData = await cacheProvider.GetAsync<SampleCollection>(cacheKey);
if (cachedData is not null) { return cachedData; }
var sample = await this.repository.FindByIdAsync(_id);
await cacheProvider.SetAsync(cacheKey, sample, TimeSpan.FromMinutes(cacheSettings.DefaultCacheDurationInMinutes));
return sample;
}
public async ValueTask<IEnumerable<SampleCollection>> GetAllSamples(CancellationToken cancellationToken)
{
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllSamples");
var cachedData = await cacheProvider.GetAsync<IEnumerable<SampleCollection>>(cacheKey) ?? [];
if (cachedData.Any()) return cachedData;
var samples = await this.repository.AsQueryable();
await cacheProvider.SetAsync(cacheKey, samples, TimeSpan.FromMinutes(cacheSettings.DefaultCacheDurationInMinutes));
return samples;
}
public async ValueTask<SampleCollection> UpdateSample(string _id, SampleCollection entity, CancellationToken cancellationToken)
{
await this.repository.ReplaceOneAsync(entity);
await ResetCollectionCache();
return entity;
}
public async ValueTask<SampleCollection> DeleteSample(string _id, CancellationToken cancellationToken)
{
var entity = await this.repository.DeleteOneAsync(doc => doc._Id == _id);
await ResetCollectionCache();
return entity;
}
/// <summary>
/// Temporary method to "reset" collections cache
/// </summary>
/// <returns></returns>
private async Task ResetCollectionCache()
{
//TODO: remoge this mehtod when necessary.
var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllSamples");
await cacheProvider.SetAsync(cacheKey, Enumerable.Empty<SampleCollection>(), null);
}
}
}