RhSolutions-AddIn/RhSolutions.AddIn/Services/DatabaseClient.cs
2023-04-20 09:37:07 +03:00

49 lines
1.3 KiB
C#

using Newtonsoft.Json;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace RhSolutions.Services;
public class DatabaseClient : IDatabaseClient
{
private readonly IServiceProvider serviceProvider;
public HttpStatusCode StatusCode { get; private set; }
public DatabaseClient(IServiceProvider provider)
{
this.serviceProvider = provider;
}
public async Task<IEnumerable<Product>> GetProducts(string line)
{
string request;
if (ProductSku.TryParse(line, out var skus))
{
request = @"https://rh.cebotari.ru/api/products/" + skus.FirstOrDefault().ToString();
}
else
{
request = @"https://rh.cebotari.ru/api/search?query=" + line;
}
var client = serviceProvider.GetRequiredService<HttpClient>();
var response = await client.GetAsync(request);
try
{
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<IEnumerable<Product>>(json) ?? Enumerable.Empty<Product>();
}
catch
{
StatusCode = response.StatusCode;
}
return Enumerable.Empty<Product>();
}
}