Files
ersatztv/ErsatzTV.Application/Scheduling/Commands/CreateDecoTemplateGroupHandler.cs
T
Jason DoveandGitHub 5d081ceeff fix editorconfig and run code cleanup (#2324)
* fix formatting rules

* reformat ersatztv

* reformat ersatztv.application

* reformat ersatztv.core

* refactor ersatztv.core.tests

* reformat ersatztv.ffmpeg

* reformat ersatztv.ffmpeg.tests

* reformat ersatztv.infrastructure

* cleanup infra mysql

* cleanup infra sqlite

* cleanup infra tests

* cleanup ersatztv.scanner

* cleanup ersatztv.scanner.tests

* sln cleanup

* update dependencies
2025-08-16 14:44:48 +00:00

51 lines
2.2 KiB
C#

using ErsatzTV.Core;
using ErsatzTV.Core.Domain.Scheduling;
using ErsatzTV.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;
namespace ErsatzTV.Application.Scheduling;
public class CreateDecoTemplateGroupHandler(IDbContextFactory<TvContext> dbContextFactory)
: IRequestHandler<CreateDecoTemplateGroup, Either<BaseError, DecoTemplateGroupViewModel>>
{
public async Task<Either<BaseError, DecoTemplateGroupViewModel>> Handle(
CreateDecoTemplateGroup request,
CancellationToken cancellationToken)
{
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
Validation<BaseError, DecoTemplateGroup> validation = await Validate(dbContext, request);
return await validation.Apply(profile => PersistDecoTemplateGroup(dbContext, profile));
}
private static async Task<DecoTemplateGroupViewModel> PersistDecoTemplateGroup(
TvContext dbContext,
DecoTemplateGroup decoDecoTemplateGroup)
{
await dbContext.DecoTemplateGroups.AddAsync(decoDecoTemplateGroup);
await dbContext.SaveChangesAsync();
return Mapper.ProjectToViewModel(decoDecoTemplateGroup);
}
private static Task<Validation<BaseError, DecoTemplateGroup>> Validate(
TvContext dbContext,
CreateDecoTemplateGroup request) =>
ValidateName(dbContext, request).MapT(name => new DecoTemplateGroup { Name = name, DecoTemplates = [] });
private static async Task<Validation<BaseError, string>> ValidateName(
TvContext dbContext,
CreateDecoTemplateGroup createDecoTemplateGroup)
{
Validation<BaseError, string> result1 = createDecoTemplateGroup.NotEmpty(c => c.Name)
.Bind(_ => createDecoTemplateGroup.NotLongerThan(50)(c => c.Name));
int duplicateNameCount = await dbContext.DecoTemplateGroups
.CountAsync(ps => ps.Name == createDecoTemplateGroup.Name);
var result2 = Optional(duplicateNameCount)
.Where(count => count == 0)
.ToValidation<BaseError>("Deco template group name must be unique");
return (result1, result2).Apply((_, _) => createDecoTemplateGroup.Name);
}
}