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.
Server-Panel/Services/HttpUsersService.cs

72 lines
2.4 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 ListUsersResponseDto(List<User> Users, uint TotalCount);
public async Task<(uint, List<User>)> ListUsers(uint from, uint len, string? searchString = null)
{
var httpResponse =
await Client.GetAsync($"/api/admin/list-users?start={from}&n={len}&search={searchString ?? ""}");
await ErrorsUtils.EnsureResponseIsOk(httpResponse);
var response = await httpResponse.Content.ReadFromJsonAsync<ListUsersResponseDto>()
?? throw new Exception("Received non-parseable json from server");
return (response.TotalCount, response.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("/api/admin/user/add",
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("/api/admin/user/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.PostAsJsonAsync($"/api/admin/user/{user.Id}/update",
new UpdateUserRequestDto(user.Email, user.Name, user.IsAdmin));
await ErrorsUtils.EnsureResponseIsOk(httpResponse);
}
}