constellation-api/CH.CQRS/Command/Energy/CreateEnergyProviderCommand.cs

43 lines
1.4 KiB
C#

using CH.CQRS.Service.Energy;
using CH.CQRS.Service.Energy.Options;
using CH.Dal;
using CH.Dal.DbEntity;
using CH.Dal.Validators;
using FluentValidation;
using Microsoft.EntityFrameworkCore;
using OpenHarbor.CQRS.Abstractions;
namespace CH.CQRS.Command.Energy;
public class CreateEnergyProviderCommand
{
public required string Name { get; set; }
public bool Active { get; set; }
}
public class CreateEnergyProviderCommandHandler(EnergyService energyService) : ICommandHandler<CreateEnergyProviderCommand>
{
public Task HandleAsync(CreateEnergyProviderCommand command, CancellationToken cancellationToken = new CancellationToken())
{
return energyService.CreateEnergyProviderAsync(new CreateEnergyProviderCommandOptions
{
Name = command.Name,
Active = command.Active
},cancellationToken);
}
}
public class CreateEnergyProviderCommandValidator : AbstractValidator<CreateEnergyProviderCommand>
{
public CreateEnergyProviderCommandValidator(CHDbContext dbContext)
{
RuleFor(command => command.Name)
.NotEmpty()
.MinimumLength(3)
.MustAsync(async (name, cancellationToken) =>
{
var nameInUse = await dbContext.EnergyProviders.AnyAsync(energyProvider => energyProvider.Name == name, cancellationToken);
return false == nameInUse;
})
.WithMessage("This Name is already in use by another energy provider.");
}
}