Files
MilkyShots/MilkStream.Client/Services/UserService.cs
T

73 lines
3.0 KiB
C#

using Butter.Dtos.User;
using Microsoft.Extensions.Options;
namespace MilkStream.Client.Services;
/// <summary>
/// Manages user profile operations via the API.
/// </summary>
public sealed class UserService(
IOptions<ServiceOptions> options,
IHttpClientFactory httpClientFactory,
LoginService loginService,
ILogger<UserService> logger
) : AuthServiceBase(options, httpClientFactory, loginService, logger) {
/// <summary>
/// Gets the currently authenticated user's profile.
/// </summary>
/// <returns>The user info, or null if not logged in or request failed.</returns>
public async Task<UserInfoDto?> GetUserAsync() {
if (LoginService.AuthInfo == null) return null;
return await GetJsonAsync<UserInfoDto>($"api/user/{LoginService.AuthInfo.UserId}");
}
/// <summary>
/// Gets all users (admin only on the server side).
/// </summary>
/// <returns>A list of all users, or null if the request failed.</returns>
public Task<List<UserInfoDto>?> GetAllUsersAsync() =>
GetJsonAsync<List<UserInfoDto>>("api/user");
/// <summary>
/// Gets a user by their ID.
/// </summary>
/// <param name="id">The user ID.</param>
/// <returns>The user info, or null if not found or request failed.</returns>
public Task<UserInfoDto?> GetUserByIdAsync(Guid id) =>
GetJsonAsync<UserInfoDto>($"api/user/{id}");
/// <summary>
/// Updates an existing user.
/// </summary>
/// <param name="dto">The user update data.</param>
/// <returns>The updated user info and an optional error message.</returns>
public async Task<(UserInfoDto? Result, string? Error)> UpdateUserAsync(UserUpdateDto dto) {
var response = await Client.PostAsJsonAsync("api/user/update", dto).ConfigureAwait(false);
if (response.IsSuccessStatusCode) return (await response.Content.ReadFromJsonAsync<UserInfoDto>().ConfigureAwait(false), null);
var error = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return (null, error);
}
/// <summary>
/// Soft-deletes a user by their ID (admin only on the server side).
/// </summary>
/// <param name="id">The user ID.</param>
/// <returns>True if the user was deleted, false otherwise.</returns>
public async Task<bool> DeleteUserAsync(Guid id) {
var response = await Client.DeleteAsync($"api/user/{id}").ConfigureAwait(false);
return response.IsSuccessStatusCode;
}
/// <summary>
/// Creates a new user (admin only on the server side).
/// </summary>
/// <param name="dto">The user creation data.</param>
/// <returns>The new user ID, or null if the request failed.</returns>
public async Task<Guid?> CreateUserAsync(UserCreateDto dto) {
var response = await Client.PutAsJsonAsync("api/user", dto).ConfigureAwait(false);
if (response.IsSuccessStatusCode) return await response.Content.ReadFromJsonAsync<Guid>().ConfigureAwait(false);
return null;
}
}