96 lines
3.2 KiB
C#
96 lines
3.2 KiB
C#
using Microsoft.Extensions.Caching.Memory;
|
|
using Newtonsoft.Json;
|
|
using System.Web;
|
|
using System.Net;
|
|
using System.Net.Http;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.AspNetCore.Http.Extensions;
|
|
|
|
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<IEnumerable<Product>> 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<Product> 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;
|
|
return Enumerable.Empty<Product>();
|
|
}
|
|
|
|
var cacheEntryOptions = new MemoryCacheEntryOptions()
|
|
.SetSlidingExpiration(TimeSpan.FromHours(1));
|
|
_memoryCache.Set(sku, products, cacheEntryOptions);
|
|
return products;
|
|
}
|
|
else
|
|
{
|
|
return products;
|
|
}
|
|
}
|
|
|
|
else
|
|
{
|
|
QueryBuilder qb = new()
|
|
{
|
|
{"query", line}
|
|
};
|
|
string request = @"https://rh.cebotari.ru/api/search" + qb.ToQueryString();
|
|
|
|
if (!_memoryCache.TryGetValue(line, out IEnumerable<Product> 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;
|
|
return Enumerable.Empty<Product>();
|
|
}
|
|
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
} |