RhSolutions-AddIn/RhSolutions.AddIn/Services/RhDatabaseClient.cs
2023-03-27 15:52:28 +03:00

57 lines
1.6 KiB
C#

using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using RhSolutions;
using RhSolutions.AddIn;
using RhSolutions.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace RhSolutions.Services
{
public class RhDatabaseClient : IDatabaseClient
{
private IServiceProvider serviceProvider;
public HttpStatusCode StatusCode { get; private set; }
public RhDatabaseClient(IServiceProvider provider)
{
this.serviceProvider = provider;
}
public async Task<IEnumerable<Product>> GetProducts(string line)
{
string request;
if (Sku.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>();
}
}
}