RhSolutions-AddIn/RhSolutions.AddIn/Services/RhDatabaseClient.cs

49 lines
1.3 KiB
C#
Raw Normal View History

2023-04-07 07:27:42 +03:00
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;
public class RhDatabaseClient : IDatabaseClient
2022-12-20 12:03:05 +03:00
{
2023-04-07 07:27:42 +03:00
private readonly IServiceProvider serviceProvider;
public HttpStatusCode StatusCode { get; private set; }
public RhDatabaseClient(IServiceProvider provider)
2022-12-20 12:03:05 +03:00
{
2023-04-07 07:27:42 +03:00
this.serviceProvider = provider;
}
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;
if (ProductSku.TryParse(line, out var skus))
2023-03-27 13:55:58 +03:00
{
2023-04-07 07:27:42 +03:00
request = @"https://rh.cebotari.ru/api/products/" + skus.FirstOrDefault().ToString();
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;
2022-12-20 12:03:05 +03:00
}
2023-04-07 07:27:42 +03:00
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>();
2022-12-20 12:03:05 +03:00
}
}