Adding
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using LCU.API.Collections.RepoApi.Exceptions;
|
||||
using Newtonsoft.Json;
|
||||
using Serilog;
|
||||
|
||||
namespace LCU.API.Collections.RepoApi.DataAccess
|
||||
{
|
||||
public abstract class DaoClient
|
||||
{
|
||||
private readonly IHttpClientFactory _clientFactory;
|
||||
|
||||
protected DaoClient(IHttpClientFactory clientFactory)
|
||||
{
|
||||
_clientFactory = clientFactory;
|
||||
}
|
||||
|
||||
public async Task<T> RetrieveByIdentifierAsync<T>(string url, string identifier)
|
||||
{
|
||||
// Temporary log to illustrate this working completely
|
||||
Log.Information($"Retrieve Async called for {typeof(T).Name} with {url}");
|
||||
using (var client = _clientFactory.CreateClient())
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
try
|
||||
{
|
||||
var retrievedObject = JsonConvert.DeserializeObject<T>(
|
||||
await response.Content.ReadAsStringAsync());
|
||||
|
||||
return retrievedObject;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error(ex,$"Error Deserializing {typeof(T).Name} for {identifier}");
|
||||
throw new ServerErrorException();
|
||||
}
|
||||
}
|
||||
|
||||
if (response.StatusCode == HttpStatusCode.NotFound)
|
||||
{
|
||||
return default(T);
|
||||
}
|
||||
|
||||
Log.Error($"Retrieve {typeof(T).Name} Bad Status Code {response.StatusCode}, for { url}");
|
||||
throw new MissingRequirementException(typeof(T).Name, $"Failed to retrieve {typeof(T).Name} for {identifier}");
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<T> RetrieveAllAsync<T>(string url)
|
||||
{
|
||||
// Temporary log
|
||||
Log.Information($"Retrieve All Async called for {typeof(T).Name} with {url}");
|
||||
using (var client = _clientFactory.CreateClient())
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
var response = await client.SendAsync(request);
|
||||
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
try
|
||||
{
|
||||
var retrievedObject = JsonConvert.DeserializeObject<T>(
|
||||
await response.Content.ReadAsStringAsync());
|
||||
|
||||
return retrievedObject;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error(ex,$"Error Deserializing {typeof(T).Name} for {url}");
|
||||
throw new ServerErrorException();
|
||||
}
|
||||
}
|
||||
|
||||
Log.Error($"Retrieve {typeof(T).Name} Bad Status Code {response.StatusCode}, for { url}");
|
||||
throw new MissingRequirementException(typeof(T).Name, $"Failed to retrieve {typeof(T).Name} for {url}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user