Bolt.RequestBus : How to validate request – Part 2

This is second part of the series. If you don’t know what Bolt.RequestBus is please read the previous post. In this part I am trying to show how you can add validation for your request.

In our previous example we add feature to create new book. But there is a problem. you can create a new book with empty title, author and zero price. The endpoint also allow you to add book with same title. So we need to add validation to stop anything like this to happen.

Bolt.RequestBus library allow you to add more than one validator and give them a order and they will be evaluated based on order and stop executing next validation. So we gonna create two validators for our “CreateBookRequest” command. One validator will just validate input e.g title cannot be empty. The second validator will check for duplicate title. I am using Bolt.Validation library as validation helper. You can use you own validator framwork. Lets see the validator classes.

public class InputValidator : ValidatorBase<CreateBookRequest>
{
    public override IEnumerable<IError> Validate(CreateBookRequest request)
    {
        return Bolt.Validation.RuleChecker<CreateBookRequest>
            .For(request)
            .Check(p => p.Title).NotEmpty()
            .Check(p => p.Author).NotEmpty()
            .Check(p => p.Price).GreaterThan(0)
            .ToRequestValidationErrors();
    }
}

public class UniqueBookValidator : ValidatorBase<CreateBookRequest>
{
    private readonly IBookRepository repository;

    public UniqueBookValidator(IBookRepository repository)
    {
        this.repository = repository;
    }

    public override IEnumerable<IError> Validate(CreateBookRequest request)
    {
        return RuleChecker<CreateBookRequest>.For(request)
            .Check(p => p.Title)
                .ErrorMessage(&quot;Book with same title already exists&quot;)
                .That(IsTitleUniqueInStore)
            .ToRequestValidationErrors();
    }

    private bool IsTitleUniqueInStore(string title)
    {
        return repository.GetByTitle(title) == null;
    }

    public override int Order => 1;
}

Please not that UniqueBookValidator override the order from 0 to 1. That means Input validator will execute before UniqueBookValidator. Default order of validator is 0 if you don’t override.

Now you create all your validation required for CreateBookRequest command. Next remaining thing is to tell your ioc container to register any class that ends with “Validator” so that you don’t need to register them one by one. Update
ConventionBasedModule class mentioned in previous post as below:

public class ConventionBasedModule : Module
{
    protected override void Load(ContainerBuilder builder)
    {
        var assemblies = new[]
        {typeof (Startup).Assembly};
 
        builder.RegisterAssemblyTypes(assemblies)
            .Where(a => a.IsClass && 
                    (a.Name.EndsWith(&quot;Handler&quot;)                
                    || a.Name.EndsWith(&quot;Validator&quot;))
            )
            .AsImplementedInterfaces();
 
        builder.RegisterAssemblyTypes(assemblies)
            .AssignableTo<IStartUpTask>()
            .AsImplementedInterfaces();
         
    }
}

Thats it. Now if you want to create a new book you should get a 400 httpstatus code and validation errors in body. You can download the sample application from here. Next post I will try to show how to publish events and handle events.

Here are links for other posts in these series

Happy coding 🙂

Advertisements

2 thoughts on “Bolt.RequestBus : How to validate request – Part 2

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s