Database-dependent validations using Flunt

Asked

Viewed 52 times

1

We are using Flunt and we are in doubt how to make a notification from a validation that needs to go to the bank. We have made an implementation and would like to see how best to do this: For example, let’s assume the following rule: You can’t register repeated code.

  1. In Handle, we call the Validate method, passing as parameter the interface of the repository that will be consulted:

command.Validate(_testeRepository);

  1. In the command, in the Validate method, we call Addnotifications with the contract class, also passing the repository interface that will be consulted:

    public void Validate(ITesteRepository testeRepository)
    {
        AddNotifications(new CriarTesteCommandContract(this, testeRepository));
    }
    
  2. We create a class to query the database via repository and check if the code already exists. The Isvalid() method returns the result. We did that because we will use that validation in the amendment as well:

public class ExisteCodigo 
    { 
        private string _codigo; 
        private ITesteRepository _testeRepository; 

        public ExisteCodigo( 
            string codigo, 
            ITesteRepository testeRepository) 
        { 
            _codigo = codigo; 
            _testeRepository = testeRepository; 
        } 
        public async Task<bool> IsValid()
        {
            var teste = await _testeRepository.GetByCodigoAsync(_codigo);
            return teste is not null;
        }
    }
  1. In the contract class, in the Validateasync method, we call the class created above to check the condition of the code in the database. Hence, we add the notification or not according to the result:
public CriarTesteCommandContract ( 
            CriarTesteCommand criarTesteCommand, 
            ITesteRepository testeRepository) 
        { 
            Requires() 
                .IsNotEmpty(criarTesteCommand.Codigo, "Codigo", "Código é obrigatório") 
            _ = ValidateAsync(criarTesteCommand, testeRepository); 
        } 

        private async Task ValidateAsync( 
            CriarTesteCommand criarTesteCommand, 
            ITesteRepository testeRepository) 
        { 
            var existeCodigo = await new ExisteCodigo(
                   criarTesteCommand.Codigo,
                   testeRepository)
                   .IsValid(); 
            Requires() 
                .IsFalse(existeCodigo, "Codigo", "Já existe código cadastrado"); 
        } 

There is a better way to implement database-dependent validations?

1 answer

-1

I don’t know much about Flunt, but in the new version you can inherit and create a new condition? for example:

.Requires() .Notexistsinrepo(Item, Item, condition, "item", "Item already exists")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.