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.
OptifitWebService/Server/Services/UsersService.cs

72 lines
2.1 KiB

using Infrastructure;
using Infrastructure.Repositories;
using Server.Dto.Response;
using Server.IServices;
using AutoMapper;
using Azure;
using Infrastructure.Entities;
using Server.Dto.Request;
using Shared;
namespace Server.Services;
public class UsersService : IUsersService
{
private readonly OptifitDbContext _context;
private readonly IUserRepository _userRepository;
private readonly IMapper _mapper;
public UsersService(OptifitDbContext context, IUserRepository userRepository, IMapper mapper)
{
_context = context;
_userRepository = userRepository;
_mapper = mapper;
}
public async Task<ResponseUserDto?> GetUserById(string id)
{
var userEntity = await _userRepository.GetByIdAsync(id);
if (userEntity == null)
{
return null;
}
var userDto = _mapper.Map<ResponseUserDto>(userEntity);
return userDto;
}
public async Task<PaginatedResult<ResponseUserDto>> GetUsers(int page, int size, bool ascending = true)
{
var users = await _userRepository.GetPaginatedListAsync(page - 1, size, null, null);
var result = _mapper.Map<PaginatedResult<ResponseUserDto>>(users);
return result;
}
public async Task<ResponseUserDto?> CreateUser(RequestUserDto request)
{
var user = _mapper.Map<User>(request);
await _userRepository.InsertAsync(user);
await _context.SaveChangesAsync();
return _mapper.Map<ResponseUserDto>(user);
}
public async Task<ResponseUserDto?> UpdateUser(string id,RequestUserDto request)
{
var user = await _userRepository.GetByIdAsync(id);
if (user == null) return null;
_mapper.Map(request, user);
_userRepository.Update(user);
await _context.SaveChangesAsync();
return _mapper.Map<ResponseUserDto>(user);
}
public async Task<bool> DeleteUser(string id)
{
var user = await _userRepository.GetByIdAsync(id);
if (user == null) return false;
_userRepository.Delete(id);
await _context.SaveChangesAsync();
return true;
}
}