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; using Microsoft.Extensions.Options; namespace Core.Blueprint.DAL.Mongo.Service { public class MongoSampleService : IMongoSampleService { private readonly CollectionRepository repository; private readonly CacheSettings cacheSettings; private readonly IRedisCacheProvider cacheProvider; public MongoSampleService(CollectionRepository repository, IRedisCacheProvider cacheProvider, IOptions cacheSettings) { this.repository = repository; this.repository.CollectionInitialization(); this.cacheSettings = cacheSettings.Value; this.cacheProvider = cacheProvider; } public async ValueTask CreateSample(SampleRequest newSample, CancellationToken cancellationToken) { var sampleCollection = newSample.Adapt(); await this.repository.InsertOneAsync(sampleCollection); return sampleCollection; } public async ValueTask GetSampleById(string _id, CancellationToken cancellationToken) { var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetSampleById", _id); var cachedData = await cacheProvider.GetAsync(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> GetAllSamples(CancellationToken cancellationToken) { var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllSamples"); var cachedData = await cacheProvider.GetAsync>(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 UpdateSample(string _id, SampleCollection entity, CancellationToken cancellationToken) { await this.repository.ReplaceOneAsync(entity); return entity; } public async ValueTask DeleteSample(string _id, CancellationToken cancellationToken) { var entity = await this.repository.DeleteOneAsync(doc => doc._Id == _id); return entity; } } }