97 lines
2.9 KiB
C#
97 lines
2.9 KiB
C#
using OnProfNext.Shared.Models;
|
|
using OnProfNext.Shared.Models.DTOs;
|
|
using System.Net.Http.Json;
|
|
|
|
namespace OnProfNext.Client.Services
|
|
{
|
|
public class UserApiService
|
|
{
|
|
private readonly HttpClient _httpClient;
|
|
|
|
public UserApiService(HttpClient httpClient)
|
|
{
|
|
_httpClient = httpClient;
|
|
}
|
|
|
|
public async Task<(bool Success, List<UserDto>? Data, string? Error)> GetUsersAsync()
|
|
{
|
|
try
|
|
{
|
|
var users = await _httpClient.GetFromJsonAsync<List<UserDto>>("api/users");
|
|
return (true, users ?? new List<UserDto>(), null);
|
|
}
|
|
catch (HttpRequestException)
|
|
{
|
|
return (false, null, "Keine Verbindung zum Server. Bitte später erneut versuchen.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return (false, null, $"Unerwarteter Fehler: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
public async Task<(bool Success, string? Error)> CreateUserAsync(User user)
|
|
{
|
|
try
|
|
{
|
|
var response = await _httpClient.PostAsJsonAsync("api/users", user);
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
return (false, $"Fehler beim Anlegen: {response.ReasonPhrase}");
|
|
}
|
|
|
|
return (true, null);
|
|
}
|
|
catch (HttpRequestException)
|
|
{
|
|
return (false, "Server nicht erreichbar.");
|
|
}
|
|
}
|
|
|
|
|
|
public async Task<(bool Success, string? Error)> UpdateUserAsync(UserDto user)
|
|
{
|
|
try
|
|
{
|
|
var response = await _httpClient.PutAsJsonAsync($"api/users/{user.Id}", user);
|
|
|
|
if(!response.IsSuccessStatusCode)
|
|
{
|
|
return (false, $"Fehler beim Aktualisieren: {response.ReasonPhrase}");
|
|
}
|
|
return (true, null);
|
|
}
|
|
|
|
catch (HttpRequestException)
|
|
{
|
|
return (false, "Server nicht erreichbar.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return (false, ex.Message);
|
|
}
|
|
}
|
|
|
|
public async Task<(bool Success, string? Error)> DeleteUserAsync(int userId)
|
|
{
|
|
try
|
|
{
|
|
var response = await _httpClient.DeleteAsync($"api/users/{userId}");
|
|
if (!response.IsSuccessStatusCode)
|
|
{
|
|
return (false, $"Fehler beim Löschen: {response.ReasonPhrase}");
|
|
}
|
|
return (true, null);
|
|
}
|
|
catch (HttpRequestException)
|
|
{
|
|
return (false, "Server nicht erreichbar.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
return (false, ex.Message);
|
|
}
|
|
}
|
|
}
|
|
}
|