Monday, 12 October 2015

Add FluentValidation Rules to Swagger Schema

The following code uses the FluentValidation IValidator profiles to add extra data to the swagger schema such as required and min/max lengths.

usage

c.SchemaFilter<AddFluentValidationRules>();

Code

public class AddFluentValidationRules : ISchemaFilter
    {
        public void Apply(Schema schema, SchemaRegistry schemaRegistry, Type type)
        {
            var validator = GetValidator(type);
 
            if (validator == null)
            {
                return;
            }
 
            schema.required = new List<string>();
 
            var validatorDescriptor = validator.CreateDescriptor();
 
            foreach (var key in schema.properties.Keys)
            {
                foreach (var propertyValidator in validatorDescriptor.GetValidatorsForMember(key))
                {
                    if (propertyValidator is NotEmptyValidator)
                    {
                        schema.required.Add(key);
                    }
 
                    if (propertyValidator is LengthValidator)
                    {
                        var lengthValidator = (LengthValidator) propertyValidator;
                        if (lengthValidator.Max > 0)
                        {
                            schema.properties[key].maxLength = lengthValidator.Max;
                        }
 
                        schema.properties[key].minLength = lengthValidator.Min;
                    }
 
                    if (propertyValidator is RegularExpressionValidator)
                    {
                        var regexExpressionValidator = (RegularExpressionValidator) propertyValidator;
                        schema.properties[key].pattern = regexExpressionValidator.Expression;
                    }
                }
                
            }
        }
 
        private IValidator GetValidator(Type t)
        {
            // use IoC or FluentValidatorFactory to get AbstractValidator<T> instance
        }
    }