RhSolutions-AddIn/RhSolutions.AddIn/Services/DatabaseClient.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;
2023-04-20 09:37:07 +03:00
public class DatabaseClient : 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; }
2023-04-20 09:37:07 +03:00
public DatabaseClient(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
}
}