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) { string request; IEnumerable products; if (ProductSku.TryParse(line, out var skus)) { ProductSku sku = skus.FirstOrDefault(); request = @"https://rh.cebotari.ru/api/products/" + sku.ToString(); if (!_memoryCache.TryGetValue(sku, out 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; } var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromHours(1)); _memoryCache.Set(sku, products, cacheEntryOptions); } } else { request = @"https://rh.cebotari.ru/api/search?query=" + line; if (!_memoryCache.TryGetValue(line, out 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; } var cacheEntryOptions = new MemoryCacheEntryOptions() .SetSlidingExpiration(TimeSpan.FromHours(1)); _memoryCache.Set(line, products, cacheEntryOptions); if (products.Count() > 0) { _memoryCache.Set(products.First(), products, cacheEntryOptions); } } } return products; } }