feat: refactor external input handling code

- refactor import/export code
- make import/export use the same JSON parsing as API
- make Patch.AssertIsValid actually useful
This commit is contained in:
spiral
2021-08-25 21:43:31 -04:00
parent f912805ecc
commit 4b944e2b20
18 changed files with 619 additions and 694 deletions

View File

@@ -1,17 +1,48 @@
using System;
using System.Text.RegularExpressions;
namespace PluralKit.Core
{
public class InvalidPatchException : Exception
{
public InvalidPatchException(string message) : base(message) {}
}
public abstract class PatchObject
{
public abstract UpdateQueryBuilder Apply(UpdateQueryBuilder b);
public void CheckIsValid() {}
public void AssertIsValid() {}
protected bool AssertValid(string input, string name, int maxLength, Func<string, bool>? validate = null)
{
if (input.Length > maxLength)
throw new FieldTooLongError(name, maxLength, input.Length);
if (validate != null && !validate(input))
throw new ValidationError(name);
return true;
}
protected bool AssertValid(string input, string name, string pattern)
{
if (!Regex.IsMatch(input, pattern))
throw new ValidationError(name);
return true;
}
}
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})")
{
Name = name;
MaxLength = maxLength;
ActualLength = actualLength;
}
}
}