Refactoring

This commit is contained in:
Sergey Chebotar 2023-04-07 07:27:42 +03:00
parent 75cb3c4f5d
commit c86f0b8143

View File

@ -1,57 +1,49 @@
using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json;
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;
using System.Net.Http; using System.Net.Http;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace RhSolutions.Services namespace RhSolutions.Services;
public class RhDatabaseClient : IDatabaseClient
{ {
public class RhDatabaseClient : IDatabaseClient private readonly IServiceProvider serviceProvider;
public HttpStatusCode StatusCode { get; private set; }
public RhDatabaseClient(IServiceProvider provider)
{ {
private IServiceProvider serviceProvider; this.serviceProvider = provider;
public HttpStatusCode StatusCode { get; private set; } }
public RhDatabaseClient(IServiceProvider provider) public async Task<IEnumerable<Product>> GetProducts(string line)
{
string request;
if (Sku.TryParse(line, out var skus))
{ {
this.serviceProvider = provider; request = @"https://rh.cebotari.ru/api/products/" + skus.FirstOrDefault().ToString();
} }
public async Task<IEnumerable<Product>> GetProducts(string line) else
{ {
string request; request = @"https://rh.cebotari.ru/api/search?query=" + line;
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>();
} }
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>();
} }
} }