csharpfritz / InstantAPIs

A library that generates Minimal API endpoints for an Entity Framework context.
MIT License
449 stars 58 forks source link

Validation layer #61

Open ScottKane opened 2 years ago

ScottKane commented 2 years ago

It would be nice if this whole process could be like a pluggable pipeline (kind of like middleware) where I can just slot in additional functionality. So initial example would just be to add a fluent validator based on each db model and use attributes like [Required] or [MaxLength(500)] to hint to the validation rules that will apply for that object.

public class MyClass
{
    [Required]
    public string Name { get; set; }
    [MaxLength(500)]
    public string Description { get; set; }
}

public class MyClassValidator : AbstractValidator<MyClass>
{
    public MyClassValidator()
    {
        RuleFor(request => request.Name)
            .Must(x => !string.IsNullOrWhiteSpace(x))
            .WithMessage(x => "Name is required!");
        RuleFor(request => request.Description)
                .MaximumLength(500)
                .WithMessage(x => "Description must be less than 500 characters!");
    }
}
csharpfritz commented 2 years ago

This is a bit of a step into creating our own DSL to generate APIs, and I would like to decline this.

Data Annotation validation should be supported by default by Minimal APIs, and inherited by InstantAPIs downstream

If a developer needs significant validation and error checking in their APIs, they can write that API directly.

ScottKane commented 2 years ago

This is a bit awkward though as the more I think about it, the less I think validation attributes belong in domain models. They are better suited at a dto level so it would be nice if anyone has any suggestions for how they think this could be done.

For me it boils down to the fact that most endpoints will have some form of validation, so if I have to hand crank all of those, where is the benefit here?

davidbuckleyni commented 2 years ago

Why would you not just use Fluent Validation seems like this would be recreating what is already available in the excellent package.