using Microsoft.Extensions.Caching.Memory; using Newtonsoft.Json; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace RhSolutions.Services; public class DatabaseClient : IDatabaseClient { private readonly HttpClient _httpClient; private readonly IMemoryCache _memoryCache; public HttpStatusCode StatusCode { get; private set; } public DatabaseClient(HttpClient httpClient, IMemoryCache memoryCache) { _httpClient = httpClient; _memoryCache = memoryCache; } public async Task> GetProducts(string line) { if (ProductSku.TryParse(line, out var skus)) { ProductSku sku = skus.FirstOrDefault(); string request = @"https://rh.cebotari.ru/api/products/" + sku.ToString(); if (!_memoryCache.TryGetValue(sku, out IEnumerable products)) { var response = await _httpClient.GetAsync(request); try { response.EnsureSuccessStatusCode(); string json = await response.Content.ReadAsStringAsync(); products = JsonConvert.DeserializeObject>(json) ?? Enumerable.Empty(); } catch { StatusCode = response.StatusCode; return Enumerable.Empty(); } var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromHours(1)); _memoryCache.Set(sku, products, cacheEntryOptions); return products; } else { return products; } } else { UriBuilder builder = new(@"https://rh.cebotari.ru/api/search") { Query = $"query={line.Replace("&", "%26")}" }; string request = builder.Uri.AbsoluteUri; if (!_memoryCache.TryGetValue(line, out IEnumerable products)) { var response = await _httpClient.GetAsync(request); try { response.EnsureSuccessStatusCode(); string json = await response.Content.ReadAsStringAsync(); products = JsonConvert.DeserializeObject>(json) ?? Enumerable.Empty(); } catch { StatusCode = response.StatusCode; return Enumerable.Empty(); } var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromHours(1)); _memoryCache.Set(line, products, cacheEntryOptions); if (products.Any()) { _memoryCache.Set(products.First(), products, cacheEntryOptions); } return products; } else { return products; } } } }