Coursework_ComputerStore_Li.../ComputerStoreEmployeeApp/APIClient.cs

83 lines
3.0 KiB
C#
Raw Normal View History

using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
using ComputerStoreDataModels.Models;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Text;
namespace ComputerStoreEmployeeApp
{
public class APIClient
{
private static readonly HttpClient _client = new();
public static EmployeeViewModel? Employee { get; set; } = null;
public static Dictionary<int, (IComponentModel Component, int Quantity)>? productComponents;
public static Dictionary<int, (IComponentModel Component, int Quantity)>? pcComponents;
public static void Connect(IConfiguration configuration)
{
_client.BaseAddress = new Uri(configuration["IPAddress"]);
_client.DefaultRequestHeaders.Accept.Clear();
_client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public static async Task<T?> GetRequest<T>(string requestUrl)
{
var response = await _client.GetAsync(requestUrl);
var result = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
return JsonConvert.DeserializeObject<T>(result, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
}
else
{
throw new Exception(result);
}
}
public static async Task<bool> PostRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = await _client.PostAsync(requestUrl, data);
var result = response.Content.ReadAsStringAsync().Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception(result);
}
return true;
}
public static async Task<bool> PatchRequest<T>(string requestUrl, T model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json-patch+json");
var response = await _client.PatchAsync(requestUrl, data);
var result = response.Content.ReadAsStringAsync().Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception(result);
}
return Convert.ToBoolean(result);
}
public static async Task<bool> DeleteRequest<T>(string requestUrl)
{
var response = await _client.DeleteAsync(requestUrl);
var result = response.Content.ReadAsStringAsync().Result;
if (!response.IsSuccessStatusCode)
{
throw new Exception(result);
}
return Convert.ToBoolean(result);
}
}
}