ServiceStack - FluentValidation

I have a question about using FluentValidation with ServiceStack.

For example:

[Route("/customers/{Id}", "PUT")]
public class UpdateCustomer : IReturn<Customer>
{
    public int Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

[Route("/customers/{Id}", "DELETE")]
public class DeleteCustomer : IReturnVoid
{
    public int Id { get; set; }
}

public class Customer
{
    public int Id { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

      

When I update client information, I want to check, for example, all parameters, but when deleting, for example, I just want to make sure that the Id is a positive int, for example. So FirstName, LastName, etc. Everything else is not interesting to me in this case.

If I implement the FluentValidator in the Customer class, will I have to put all the logic in the validator for that (to apply different rules based on the request route)? Or is there a more elegant way to do this?

+3


source to share


1 answer


Validators should only be found in DTO requests, for example:

public class UpdateCustomerValidator : AbstractValidator<UpdateCustomer>
{
    public UpdateCustomerValidator()
    {
        RuleFor(r => r.Id).GreaterThan(0);
        RuleFor(r => r.FirstName).NotEmpty();
        RuleFor(r => r.LastName).NotEmpty();
    }
}

      

and similarly for DeleteCustomer

, for example:



public class DeleteCustomerValidator : AbstractValidator<DeleteCustomer>
{
    public DeleteCustomerValidator()
    {
        RuleFor(r => r.Id).GreaterThan(0);
    }
}

      

Although creating a whole validator for a single field might be overkill, so instead you can just add a validation to your service, like this:

public class CustomerServices : Service
{
    public void Any(DeleteCustomer request)
    {
        if (request.Id <= 0)
            throw new ArgumentException("Id Required", "Id")

        Db.DeleteById<Customer>(request.Id);
    }
}

      

+2


source







All Articles