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? productComponents; public static Dictionary? 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 GetRequest(string requestUrl) { var response = await _client.GetAsync(requestUrl); var result = response.Content.ReadAsStringAsync().Result; if (response.IsSuccessStatusCode) { return JsonConvert.DeserializeObject(result, new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }); } else { throw new Exception(result); } } public static async Task PostRequest(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 PatchRequest(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 DeleteRequest(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); } } }