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

57 lines
1.6 KiB
C#
Raw Normal View History

2023-03-27 07:12:04 +03:00
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
2023-03-27 15:52:28 +03:00
using RhSolutions;
2022-12-20 12:41:46 +03:00
using RhSolutions.AddIn;
2022-12-20 13:00:16 +03:00
using RhSolutions.Models;
2022-12-21 08:02:42 +03:00
using System;
2022-12-20 12:03:05 +03:00
using System.Collections.Generic;
using System.Linq;
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;
2022-12-20 12:27:47 +03:00
namespace RhSolutions.Services
2022-12-20 12:03:05 +03:00
{
2023-03-27 13:55:58 +03:00
public class RhDatabaseClient : IDatabaseClient
2022-12-20 12:03:05 +03:00
{
2023-03-27 15:52:28 +03:00
private IServiceProvider serviceProvider;
public HttpStatusCode StatusCode { get; private set; }
2023-03-27 13:55:58 +03:00
public RhDatabaseClient(IServiceProvider provider)
{
2023-03-27 15:52:28 +03:00
this.serviceProvider = provider;
2023-03-27 13:55:58 +03:00
}
2023-03-27 15:52:28 +03:00
public async Task<IEnumerable<Product>> GetProducts(string line)
2022-12-20 12:03:05 +03:00
{
2022-12-26 14:46:37 +03:00
string request;
2022-12-20 12:03:05 +03:00
if (Sku.TryParse(line, out var skus))
2022-12-21 08:02:42 +03:00
{
request = @"https://rh.cebotari.ru/api/products/" + skus.FirstOrDefault().ToString();
2022-12-21 08:02:42 +03:00
}
2022-12-20 12:03:05 +03:00
2022-12-21 08:02:42 +03:00
else
{
request = @"https://rh.cebotari.ru/api/search?query=" + line;
}
2022-12-20 12:03:05 +03:00
2023-03-27 15:52:28 +03:00
var client = serviceProvider.GetRequiredService<HttpClient>();
2023-03-27 07:12:04 +03:00
var response = await client.GetAsync(request);
2022-12-20 12:03:05 +03:00
2022-12-21 08:02:42 +03:00
try
2023-03-27 15:52:28 +03:00
{
response.EnsureSuccessStatusCode();
2022-12-21 08:02:42 +03:00
string json = await response.Content.ReadAsStringAsync();
2023-03-27 15:52:28 +03:00
return JsonConvert.DeserializeObject<IEnumerable<Product>>(json) ?? Enumerable.Empty<Product>();
2022-12-20 12:03:05 +03:00
}
2023-03-27 13:55:58 +03:00
2022-12-21 08:02:42 +03:00
catch
2022-12-20 12:03:05 +03:00
{
2023-03-27 15:52:28 +03:00
StatusCode = response.StatusCode;
2022-12-20 12:03:05 +03:00
}
2023-03-27 15:52:28 +03:00
return Enumerable.Empty<Product>();
2022-12-20 12:03:05 +03:00
}
}
}