RhSolutions-AddIn/RhSolutions.AddIn/Services/DatabaseClient.cs

83 lines
2.7 KiB
C#
Raw Normal View History

2023-05-16 07:43:57 +03:00
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
2023-03-27 15:52:28 +03:00
using System.Net;
2022-12-20 12:03:05 +03:00
using System.Net.Http;
using System.Threading.Tasks;
2023-04-07 07:27:42 +03:00
namespace RhSolutions.Services;
2023-04-20 09:37:07 +03:00
public class DatabaseClient : IDatabaseClient
2022-12-20 12:03:05 +03:00
{
2023-05-16 07:43:57 +03:00
private readonly HttpClient _httpClient;
private readonly IMemoryCache _memoryCache;
2023-04-07 07:27:42 +03:00
public HttpStatusCode StatusCode { get; private set; }
2023-05-16 07:43:57 +03:00
public DatabaseClient(HttpClient httpClient, IMemoryCache memoryCache)
2022-12-20 12:03:05 +03:00
{
2023-05-16 07:43:57 +03:00
_httpClient = httpClient;
_memoryCache = memoryCache;
2023-04-07 07:27:42 +03:00
}
2023-03-27 13:55:58 +03:00
2023-04-07 07:27:42 +03:00
public async Task<IEnumerable<Product>> GetProducts(string line)
{
string request;
IEnumerable<Product> products;
2023-04-07 07:27:42 +03:00
if (ProductSku.TryParse(line, out var skus))
2023-03-27 13:55:58 +03:00
{
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<IEnumerable<Product>>(json) ?? Enumerable.Empty<Product>();
}
catch
{
StatusCode = response.StatusCode;
}
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromHours(1));
_memoryCache.Set(sku, products, cacheEntryOptions);
}
2023-03-27 13:55:58 +03:00
}
2023-04-07 07:27:42 +03:00
else
2022-12-20 12:03:05 +03:00
{
2023-04-07 07:27:42 +03:00
request = @"https://rh.cebotari.ru/api/search?query=" + line;
if (!_memoryCache.TryGetValue(line, out products))
{
var response = await _httpClient.GetAsync(request);
2023-04-07 07:27:42 +03:00
try
{
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync();
products = JsonConvert.DeserializeObject<IEnumerable<Product>>(json) ?? Enumerable.Empty<Product>();
}
catch
{
StatusCode = response.StatusCode;
}
2023-05-16 07:43:57 +03:00
var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromHours(1));
_memoryCache.Set(line, products, cacheEntryOptions);
if (products.Count() > 0)
{
_memoryCache.Set(products.First(), products, cacheEntryOptions);
}
2023-05-16 07:43:57 +03:00
}
}
2023-04-07 07:27:42 +03:00
2023-05-16 07:43:57 +03:00
return products;
2022-12-20 12:03:05 +03:00
}
}