80 lines
2.8 KiB
C#
80 lines
2.8 KiB
C#
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, int)>? productComponents;
|
|
public static Dictionary<int, (IComponentModel, int)>? 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);
|
|
}
|
|
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 Convert.ToBoolean(result);
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|