46 lines
1.8 KiB
C#
46 lines
1.8 KiB
C#
using ErsatzTV.Core;
|
|
using ErsatzTV.Core.Domain;
|
|
using ErsatzTV.Core.Errors;
|
|
using ErsatzTV.Infrastructure.Data;
|
|
using ErsatzTV.Infrastructure.Extensions;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace ErsatzTV.Application.ProgramSchedules;
|
|
|
|
public class DeleteProgramScheduleHandler : IRequestHandler<DeleteProgramSchedule, Either<BaseError, Unit>>
|
|
{
|
|
private readonly IDbContextFactory<TvContext> _dbContextFactory;
|
|
|
|
public DeleteProgramScheduleHandler(IDbContextFactory<TvContext> dbContextFactory) =>
|
|
_dbContextFactory = dbContextFactory;
|
|
|
|
public async Task<Either<BaseError, Unit>> Handle(
|
|
DeleteProgramSchedule request,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
await using TvContext dbContext = await _dbContextFactory.CreateDbContextAsync(cancellationToken);
|
|
Option<ProgramSchedule> maybeProgramSchedule = await ProgramScheduleMustExist(
|
|
dbContext,
|
|
request,
|
|
cancellationToken);
|
|
return await maybeProgramSchedule.Match(
|
|
Some: programSchedule => DoDeletion(dbContext, programSchedule).Map(Right<BaseError, Unit>),
|
|
None: () => Task.FromResult<Either<BaseError, Unit>>(
|
|
new NotFoundError($"ProgramSchedule {request.ProgramScheduleId} does not exist.")));
|
|
}
|
|
|
|
private static Task<Unit> DoDeletion(TvContext dbContext, ProgramSchedule programSchedule)
|
|
{
|
|
dbContext.ProgramSchedules.Remove(programSchedule);
|
|
return dbContext.SaveChangesAsync().ToUnit();
|
|
}
|
|
|
|
private static Task<Option<ProgramSchedule>> ProgramScheduleMustExist(
|
|
TvContext dbContext,
|
|
DeleteProgramSchedule request,
|
|
CancellationToken cancellationToken) =>
|
|
dbContext.ProgramSchedules
|
|
.SelectOneAsync(ps => ps.Id, ps => ps.Id == request.ProgramScheduleId, cancellationToken)
|
|
.Map(identity);
|
|
}
|