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/SessionService.cs

71 lines
2.8 KiB

using AutoMapper;
using Infrastructure;
using Infrastructure.Entities;
using Infrastructure.Repositories;
using Server.Dto.Request;
using Server.Dto.Response;
using Server.IServices;
using Shared;
namespace Server.Services
{
public class SessionService : ISessionService
{
private readonly OptifitDbContext _context;
private readonly ISessionRepository _sessionRepository;
private readonly IExerciceRepository _exerciceRepository;
private readonly IMapper _mapper;
public SessionService(OptifitDbContext context, ISessionRepository sessionRepository, IExerciceRepository exerciceRepository, IMapper mapper)
{
_context = context;
_sessionRepository = sessionRepository;
_exerciceRepository = exerciceRepository;
_mapper = mapper;
}
public async Task<PaginatedResult<ResponseSessionDto>> GetSessions(int page, int size, bool ascending = true)
{
var sessions = await _sessionRepository.GetPaginatedListAsync(page - 1, size, null, null);
var result = _mapper.Map<PaginatedResult<ResponseSessionDto>>(sessions);
return result;
}
public async Task<ResponseSessionDto?> GetSessionById(string id)
{
var session = await _sessionRepository.GetByIdAsync(id, s => s.Exercices);
return session == null ? null : _mapper.Map<ResponseSessionDto>(session);
}
public async Task<ResponseSessionDto> CreateSession(RequestSessionDto request)
{
var session = _mapper.Map<Session>(request);
session.Exercices = (ICollection<Exercice>)await _exerciceRepository.GetAllAsync(e => request.ExerciceIds.Contains(e.Id));
await _sessionRepository.InsertAsync(session);
await _context.SaveChangesAsync();
return _mapper.Map<ResponseSessionDto>(session);
}
public async Task<ResponseSessionDto?> UpdateSession(string id, RequestSessionDto request)
{
var session = await _sessionRepository.GetByIdAsync(id, s => s.Exercices);
if (session == null) return null;
_mapper.Map(request, session);
session.Exercices = (ICollection<Exercice>)await _exerciceRepository.GetAllAsync(e => request.ExerciceIds.Contains(e.Id));
_sessionRepository.Update(session);
await _context.SaveChangesAsync();
return _mapper.Map<ResponseSessionDto>(session);
}
public async Task<bool> DeleteSession(string id)
{
var session = await _sessionRepository.GetByIdAsync(id);
if (session == null) return false;
_sessionRepository.Delete(id);
await _context.SaveChangesAsync();
return true;
}
}
}