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.
Dotnet-WebAPI/DbServices/DbUserService.cs

72 lines
2.0 KiB

using AppContext.Entities;
using Converters;
using Microsoft.EntityFrameworkCore;
using Model;
using Services;
using Services.Failures;
namespace DbServices;
public class DbUserService(AppContext.AppContext context) : UserService
{
public Task<IEnumerable<User>> ListUsers(string nameNeedle)
{
return Task.FromResult(
context.Users
.Where(n => n.Name.ToLower().Contains(nameNeedle.ToLower()))
.AsEnumerable()
.Select(e => e.ToModel())
);
}
public Task<IEnumerable<User>> ListUsers()
{
return Task.FromResult(
context.Users
.AsEnumerable()
.Select(e => e.ToModel())
);
}
public async Task<User?> GetUser(int id)
{
return (await context.Users.FirstOrDefaultAsync(e => e.Id == id))?.ToModel();
}
public async Task<User> CreateUser(string username, string email, string password, string profilePicture,
bool isAdmin)
{
var userEntity = new UserEntity
{
Name = username,
Email = email,
Password = password,
ProfilePicture = profilePicture,
IsAdmin = isAdmin
};
await context.Users.AddAsync(userEntity);
await context.SaveChangesAsync();
return userEntity.ToModel();
}
public async Task<bool> RemoveUsers(params int[] identifiers)
{
return await context.Users.Where(u => identifiers.Contains(u.Id)).ExecuteDeleteAsync() > 0;
}
public async Task UpdateUser(User user)
{
var entity = await context.Users.FirstOrDefaultAsync(e => e.Id == user.Id);
if (entity == null)
throw new ServiceException(Failure.NotFound("User not found"));
entity.ProfilePicture = user.ProfilePicture;
entity.Name = user.Name;
entity.Email = user.Email;
entity.Id = user.Id;
await context.SaveChangesAsync();
}
}