using Core.Blueprint.DAL.SQLServer; using Core.Blueprint.DAL.SQLServer.Context; using Core.Blueprint.DAL.SQLServer.Contracts; using Core.Blueprint.DAL.SQLServer.Entities; using Core.Blueprint.DAL.SQLServer.Entities.Request; using Core.Blueprint.Redis; using Core.Blueprint.Redis.Helpers; using Mapster; public class SqlSampleService : ISqlSampleService { private readonly IEntityRepository _sqlSampleRepository; private readonly ICacheSettings cacheSettings; private readonly IRedisCacheProvider cacheProvider; public SqlSampleService(IEntityRepository sqlSampleRepository, IRedisCacheProvider cacheProvider, ICacheSettings cacheSettings) { _sqlSampleRepository = sqlSampleRepository; this.cacheSettings = cacheSettings; this.cacheProvider = cacheProvider; } public async Task> GetAllSamples() { var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetAllSamples"); var cachedData = await cacheProvider.GetAsync>(cacheKey) ?? []; if (cachedData.Any()) return cachedData; var samples = await _sqlSampleRepository.GetAllAsync(); await cacheProvider.SetAsync(cacheKey, samples, TimeSpan.FromMinutes(cacheSettings.DefaultCacheDurationInMinutes)); return samples; } public async Task GetSampleById(int id) { var cacheKey = CacheKeyHelper.GenerateCacheKey(this, "GetSampleById", id); var cachedData = await cacheProvider.GetAsync(cacheKey); if (cachedData is not null) { return cachedData; } var sample = await _sqlSampleRepository.GetByIdAsync(id); await cacheProvider.SetAsync(cacheKey, sample, TimeSpan.FromMinutes(cacheSettings.DefaultCacheDurationInMinutes)); return sample; } public async Task AddSample(SampleRequest newSample) { var sample = newSample.Adapt(); await _sqlSampleRepository.AddAsync(sample); await _sqlSampleRepository.SaveAsync(); return sample; } public async Task UpdateSample(Sample sample) { var existingEntity = await _sqlSampleRepository.GetByIdAsync(sample.Id); if (existingEntity is null) return existingEntity; _sqlSampleRepository.Update(sample); await _sqlSampleRepository.SaveAsync(); return sample; } public async Task DeleteSample(int id) { var sample = await _sqlSampleRepository.GetByIdAsync(id); if (sample == null) return null; _sqlSampleRepository.Delete(sample); await _sqlSampleRepository.SaveAsync(); return sample; } }