You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
81 lines
2.6 KiB
81 lines
2.6 KiB
using System.Diagnostics;
|
|
using System.Net;
|
|
using System.Net.Http.Json;
|
|
using AdminPanel.Models;
|
|
|
|
namespace AdminPanel.Services;
|
|
|
|
public class HttpUsersService : IUsersService
|
|
{
|
|
private HttpClient Client { get; }
|
|
|
|
public HttpUsersService(HttpClient client)
|
|
{
|
|
this.Client = client;
|
|
}
|
|
|
|
|
|
private record CountRequestResult(uint Value);
|
|
|
|
public async Task<(uint, List<User>)> ListUsers(uint from, uint len, string? searchString = null)
|
|
{
|
|
var httpResponse =
|
|
await Client.GetAsync($"/admin/users?start={from}&n={len}&search={searchString ?? ""}");
|
|
await ErrorsUtils.EnsureResponseIsOk(httpResponse);
|
|
|
|
var users = await httpResponse.Content.ReadFromJsonAsync<List<User>>()
|
|
?? throw new Exception("Received non-parseable json from server");
|
|
|
|
|
|
var search = searchString != null ? $"&search={searchString}" : "";
|
|
httpResponse =
|
|
await Client.GetAsync($"/admin/users/count{search}");
|
|
await ErrorsUtils.EnsureResponseIsOk(httpResponse);
|
|
|
|
var count = await httpResponse.Content.ReadFromJsonAsync<CountRequestResult>();
|
|
|
|
return (count!.Value, users);
|
|
}
|
|
|
|
private record AddUserRequestDto(string Username, string Email, string Password, bool IsAdmin);
|
|
|
|
private record AddUserResponseDto(uint Id);
|
|
|
|
public async Task<User> AddUser(string username, string email, string password, bool isAdmin)
|
|
{
|
|
var httpResponse = await Client.PostAsJsonAsync("/admin/users",
|
|
new AddUserRequestDto(username, email, password, isAdmin));
|
|
|
|
await ErrorsUtils.EnsureResponseIsOk(httpResponse);
|
|
|
|
var response = await httpResponse.Content.ReadFromJsonAsync<AddUserResponseDto>()
|
|
?? throw new Exception("Received non-parseable json from server");
|
|
|
|
return new User
|
|
{
|
|
Name = username,
|
|
Email = email,
|
|
IsAdmin = isAdmin,
|
|
Id = response.Id
|
|
};
|
|
}
|
|
|
|
private record RemoveUsersRequestDto(uint[] Identifiers);
|
|
|
|
public async Task RemoveUsers(IEnumerable<uint> userIds)
|
|
{
|
|
var httpResponse =
|
|
await Client.PostAsJsonAsync("/admin/users/remove-all", new RemoveUsersRequestDto(userIds.ToArray()));
|
|
|
|
await ErrorsUtils.EnsureResponseIsOk(httpResponse);
|
|
}
|
|
|
|
private record UpdateUserRequestDto(string Email, string Username, bool IsAdmin);
|
|
|
|
public async Task UpdateUser(User user)
|
|
{
|
|
var httpResponse = await Client.PutAsJsonAsync($"/admin/users/{user.Id}",
|
|
new UpdateUserRequestDto(user.Email, user.Name, user.IsAdmin));
|
|
await ErrorsUtils.EnsureResponseIsOk(httpResponse);
|
|
}
|
|
} |