Files
graphql-test/Application/Services/UserService.cs
2025-11-26 16:50:06 -03:00

71 lines
2.0 KiB
C#

using Application.Exceptions;
using Application.Interfaces.Repositories;
using Application.Interfaces.Services;
using Domain.Entities;
namespace Application.Services;
public class UserService(IUserRepository repository) : IUserService
{
private IUserRepository Repository { get; } = repository;
public IEnumerable<User> GetAllUsers()
{
return Repository.GetAllUsers();
}
public User GetUserById(int id)
{
if (!Repository.TryGetUserById(id, out var user))
{
throw new ArgumentException($"User with id {id} not found");
}
return user;
}
public bool CreateUser(string username, string password, string email)
{
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(email))
{
throw new InsufficientParametersException(["username", "password", "email"]);
}
if (Repository.GetAllUsers().Any(x => x.Username == username))
{
throw new DuplicateUsernameException(username);
}
if (Repository.GetAllUsers().Any(x => x.Email == email))
{
throw new DuplicateEmailException(email);
}
var user = new User
{
Id = Repository.GetAllUsers().Count() + 1,
Username = username,
Password = password,
Email = email
};
return Repository.AddUser(user);
}
public bool UpdateUser(int id, string username, string password, string email)
{
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(email))
{
throw new InsufficientParametersException(["username", "password", "email"]);
}
if (!Repository.TryGetUserById(id, out var user))
{
throw new UserNotFoundException(id);
}
user.Email = email;
user.Password = password;
user.Username = username;
return Repository.UpdateUser(user);
}
}