Files
Readarr/src/Readarr.Http/REST/ResourceValidator.cs
Stepan Goremykin 28f64d9a46 Migrate to FluentValidation 9
(cherry picked from commit 40e54685b9e83ed24a3979bfe965c453339ad02e)
2023-05-07 17:57:58 +03:00

31 lines
1.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using FluentValidation;
using FluentValidation.Internal;
using Readarr.Http.ClientSchema;
namespace Readarr.Http.REST
{
public class ResourceValidator<TResource> : AbstractValidator<TResource>
{
public IRuleBuilderInitial<TResource, TProperty> RuleForField<TProperty>(Expression<Func<TResource, IEnumerable<Field>>> fieldListAccessor, string fieldName)
{
var rule = new PropertyRule(fieldListAccessor.GetMember(), c => GetValue(c, fieldListAccessor.Compile(), fieldName), null, () => CascadeMode.Continue, typeof(TProperty), typeof(TResource));
rule.PropertyName = fieldName;
rule.SetDisplayName(fieldName);
AddRule(rule);
return new RuleBuilder<TResource, TProperty>(rule, this);
}
private static object GetValue(object container, Func<TResource, IEnumerable<Field>> fieldListAccessor, string fieldName)
{
var resource = fieldListAccessor((TResource)container).SingleOrDefault(c => c.Name == fieldName);
return resource?.Value;
}
}
}