Untitled

mail@pastecode.io avatar
unknown
csharp
7 months ago
2.8 kB
2
Indexable
Never
using AutoMapper;
using DigitalOfficeService.Persistence.Database.Interfaces;
using DigitalOfficeService.Persistence.Database.Models;
using FluentValidation;
using LanguageExt.Common;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SERGO.Libraries.CoreService.Utils;

namespace SERGO.Cloud.DigitalOfficeService.Logic.Handler.AccessoriesHasAttribute.Commands;

[Serializable]
public record CreateAccessoriesHasAttributeCommand(
    Guid AttributeId,
    Guid AccessoriesId,
    string Value)
    : IRequest<Result<ShopAccessoriesHasAttributesEntity>>;

public class CreateAccessoriesHasAttributeHandler
    : IRequestHandler<CreateAccessoriesHasAttributeCommand, Result<ShopAccessoriesHasAttributesEntity>>
{
    private readonly IDatabaseDbContext _context;
    private readonly IMapper _mapper;

    public CreateAccessoriesHasAttributeHandler(IDatabaseDbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<Result<ShopAccessoriesHasAttributesEntity>> Handle(CreateAccessoriesHasAttributeCommand request, CancellationToken cancellationToken)
    {
        var repository = _context.Set<ShopAccessoriesHasAttributesEntity>();

        var entity = _mapper.Map<ShopAccessoriesHasAttributesEntity>(request);
        repository.Add(entity);
        await _context.SaveChangesAsync(cancellationToken);
        return entity;
    }
}

public class CreateAccessoriesHasAttributeValidator
    : AbstractValidator<CreateAccessoriesHasAttributeCommand>
{
    private readonly IDatabaseDbContext _context;

    public CreateAccessoriesHasAttributeValidator(IDatabaseDbContext context)
    {
        _context = context;

        RuleFor(x => x.AccessoriesId)
            .MustAsync(DoesAccessoriesExistsAsync)
            .WithErrorCode("accessories_not_exist")
            .WithMessage(x => $"Das Zubehör mit der Id '{x}' existiert nicht");

        RuleFor(x => x.AttributeId)
            .MustAsync(DoesAttributeExistsAsync)
            .WithErrorCode("attribute_not_exist")
            .WithMessage(x => $"Das Attribute mit der Id '{x}' existiert nicht");
    }

    private async Task<bool> DoesAttributeExistsAsync(Guid attributeId, CancellationToken cancellationToken)
    {
        var result = await _context.Set<ShopAttributesEntity>().FirstOrDefaultAsync(x => x.Id == attributeId, cancellationToken: cancellationToken);
        return result != null;
    }

    private async Task<bool> DoesAccessoriesExistsAsync(Guid accessoriesId, CancellationToken cancellationToken)
    {
        var result = await _context.Set<ShopAccessoriesSpecsEntity>().FirstOrDefaultAsync(x => x.Id == accessoriesId, cancellationToken: cancellationToken);
        return result != null;
    }
}
Leave a Comment