Fix Unsuccess Status Code return

This commit is contained in:
Serghei Cebotari 2023-10-06 15:06:42 +03:00
parent 2cb6b889b0
commit 2a0430b7ec

View File

@ -20,15 +20,12 @@ public class DatabaseClient : IDatabaseClient
public async Task<IEnumerable<Product>> GetProducts(string line) public async Task<IEnumerable<Product>> GetProducts(string line)
{ {
string request;
IEnumerable<Product> products;
if (ProductSku.TryParse(line, out var skus)) if (ProductSku.TryParse(line, out var skus))
{ {
ProductSku sku = skus.FirstOrDefault(); ProductSku sku = skus.FirstOrDefault();
request = @"https://rh.cebotari.ru/api/products/" + sku.ToString(); string request = @"https://rh.cebotari.ru/api/products/" + sku.ToString();
if (!_memoryCache.TryGetValue(sku, out products)) if (!_memoryCache.TryGetValue(sku, out IEnumerable<Product> products))
{ {
var response = await _httpClient.GetAsync(request); var response = await _httpClient.GetAsync(request);
@ -41,19 +38,25 @@ public class DatabaseClient : IDatabaseClient
catch catch
{ {
StatusCode = response.StatusCode; StatusCode = response.StatusCode;
return Enumerable.Empty<Product>();
} }
var cacheEntryOptions = new MemoryCacheEntryOptions() var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromHours(1)); .SetSlidingExpiration(TimeSpan.FromHours(1));
_memoryCache.Set(sku, products, cacheEntryOptions); _memoryCache.Set(sku, products, cacheEntryOptions);
return products;
}
else
{
return products;
} }
} }
else else
{ {
request = @"https://rh.cebotari.ru/api/search?query=" + line; string request = @"https://rh.cebotari.ru/api/search?query=" + line;
if (!_memoryCache.TryGetValue(line, out products)) if (!_memoryCache.TryGetValue(line, out IEnumerable<Product> products))
{ {
var response = await _httpClient.GetAsync(request); var response = await _httpClient.GetAsync(request);
@ -66,18 +69,22 @@ public class DatabaseClient : IDatabaseClient
catch catch
{ {
StatusCode = response.StatusCode; StatusCode = response.StatusCode;
return Enumerable.Empty<Product>();
} }
var cacheEntryOptions = new MemoryCacheEntryOptions() var cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromHours(1)); .SetSlidingExpiration(TimeSpan.FromHours(1));
_memoryCache.Set(line, products, cacheEntryOptions); _memoryCache.Set(line, products, cacheEntryOptions);
if (products.Count() > 0) if (products.Any())
{ {
_memoryCache.Set(products.First(), products, cacheEntryOptions); _memoryCache.Set(products.First(), products, cacheEntryOptions);
} }
}
}
return products; return products;
} }
else
{
return products;
}
}
}
} }