feat(apiv2): better model validation error UX
This commit is contained in:
@@ -1,50 +1,46 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
using SqlKata;
|
||||
|
||||
namespace PluralKit.Core
|
||||
{
|
||||
public abstract class PatchObject
|
||||
{
|
||||
public List<ValidationError> Errors = new();
|
||||
public abstract Query Apply(Query q);
|
||||
|
||||
public void AssertIsValid() { }
|
||||
|
||||
protected bool AssertValid(string input, string name, int maxLength, Func<string, bool>? validate = null)
|
||||
protected void AssertValid(string input, string name, int maxLength, Func<string, bool>? validate = null)
|
||||
{
|
||||
if (input.Length > maxLength)
|
||||
throw new FieldTooLongError(name, maxLength, input.Length);
|
||||
Errors.Add(new FieldTooLongError(name, maxLength, input.Length));
|
||||
if (validate != null && !validate(input))
|
||||
throw new ValidationError(name);
|
||||
return true;
|
||||
Errors.Add(new ValidationError(name));
|
||||
}
|
||||
|
||||
protected bool AssertValid(string input, string name, string pattern)
|
||||
protected void AssertValid(string input, string name, string pattern)
|
||||
{
|
||||
if (!Regex.IsMatch(input, pattern))
|
||||
throw new ValidationError(name);
|
||||
return true;
|
||||
Errors.Add(new ValidationError(name));
|
||||
}
|
||||
}
|
||||
|
||||
public class ValidationError: Exception
|
||||
{
|
||||
public ValidationError(string message) : base(message) { }
|
||||
}
|
||||
|
||||
public class FieldTooLongError: ValidationError
|
||||
{
|
||||
public string Name;
|
||||
public int MaxLength;
|
||||
public int ActualLength;
|
||||
|
||||
public FieldTooLongError(string name, int maxLength, int actualLength) :
|
||||
base($"{name} too long ({actualLength} > {maxLength})")
|
||||
public PrivacyLevel ParsePrivacy(JObject o, string propertyName)
|
||||
{
|
||||
Name = name;
|
||||
MaxLength = maxLength;
|
||||
ActualLength = actualLength;
|
||||
var input = o.Value<string>(propertyName);
|
||||
|
||||
if (input == null) return PrivacyLevel.Public;
|
||||
if (input == "") return PrivacyLevel.Private;
|
||||
if (input == "private") return PrivacyLevel.Private;
|
||||
if (input == "public") return PrivacyLevel.Public;
|
||||
|
||||
Errors.Add(new ValidationError(propertyName));
|
||||
// unused, but the compiler will complain if this isn't here
|
||||
return PrivacyLevel.Private;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user