63 lines
2.4 KiB
C#
63 lines
2.4 KiB
C#
using System.Text.Json;
|
|
using System.Net.Http.Json;
|
|
|
|
namespace Controller
|
|
{
|
|
public abstract class AbstractRepository<T, TSearch> where T : class where TSearch : class
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
public abstract string BaseUrl { get; set; }
|
|
|
|
public AbstractRepository(HttpClient httpClient)
|
|
{
|
|
_httpClient = httpClient;
|
|
}
|
|
|
|
public async Task<T> Get(int id)
|
|
{
|
|
var response = await _httpClient.GetAsync($"{BaseUrl}/{id}");
|
|
response.EnsureSuccessStatusCode();
|
|
return await response.Content.ReadFromJsonAsync<T>()
|
|
?? throw new JsonException($"Ошибка при десериализации ПРИ ПОЛУЧЕНИИ объекта {typeof(T)}");
|
|
}
|
|
|
|
public async Task<List<T>> GetAll()
|
|
{
|
|
var response = await _httpClient.GetAsync(BaseUrl);
|
|
response.EnsureSuccessStatusCode();
|
|
return await response.Content.ReadFromJsonAsync<List<T>>()
|
|
?? new List<T>();
|
|
}
|
|
public async Task<List<T>> GetFilteredList(TSearch model)
|
|
{
|
|
if (model == null)
|
|
{
|
|
return new List<T>();
|
|
}
|
|
var query = BuildQueryString(model);
|
|
var response = await _httpClient.GetAsync($"{BaseUrl}/filter{query}");
|
|
response.EnsureSuccessStatusCode();
|
|
return await response.Content.ReadFromJsonAsync<List<T>>()
|
|
?? new List<T>();
|
|
}
|
|
public async Task<T> Add(T entity)
|
|
{
|
|
var response = await _httpClient.PostAsJsonAsync(BaseUrl, entity);
|
|
response.EnsureSuccessStatusCode();
|
|
return await response.Content.ReadFromJsonAsync<T>()
|
|
?? throw new JsonException($"Ошибка при десериализации ПРИ СОЗДАНИИ объекта {typeof(T)}");
|
|
}
|
|
public async Task<T> Remove(int id)
|
|
{
|
|
var response = await _httpClient.DeleteAsync($"{BaseUrl}/{id}");
|
|
response.EnsureSuccessStatusCode();
|
|
return await response.Content.ReadFromJsonAsync<T>()
|
|
?? throw new JsonException($"Ошибка при десериализации ПРИ УДАЛЕНИИ объекта {typeof(T)}");
|
|
}
|
|
public abstract Task<T> Update(T entity);
|
|
|
|
public abstract string BuildQueryString(TSearch model);
|
|
|
|
}
|
|
}
|