103 lines
3.6 KiB
C#
Raw Normal View History

using ComputerStoreContracts.BindingModels;
using ComputerStoreContracts.ViewModels;
using ComputerStoreDataModels.Models;
2023-05-20 02:22:02 +04:00
using Microsoft.VisualBasic;
using Newtonsoft.Json;
2023-05-20 02:22:02 +04:00
using System.Net;
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)
{
2023-05-20 02:22:02 +04:00
return JsonConvert.DeserializeObject<T>(result);
}
else
{
throw new Exception(result);
}
}
2023-05-20 02:22:02 +04:00
public static Stream GetRequestFile<T>(string requestUrl, ReportComponentsBindingModel model)
{
var json = JsonConvert.SerializeObject(model);
var data = new StringContent(json, Encoding.UTF8, "application/json");
var response = _client.PostAsync(requestUrl, data).Result;
if (response.StatusCode == HttpStatusCode.OK)
{
response.Content.Headers.TryGetValues("content-type", out var type);
return response.Content.ReadAsStreamAsync().Result;
}
else
{
throw new Exception("Something went wrong!");
}
}
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;
2023-05-20 02:22:02 +04:00
}
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);
}
}
}