(feature): TryGetOperation improvements

This commit is contained in:
Maksym Sadovnychyy 2024-12-15 00:58:45 +01:00
parent b17ac0a1d7
commit d7b0145f08
2 changed files with 22 additions and 7 deletions

View File

@ -2,21 +2,34 @@
using System.ComponentModel.DataAnnotations;
using MaksIT.Core.Webapi.Models;
using System.Diagnostics.CodeAnalysis;
namespace MaksIT.Core.Abstractions.Webapi;
public abstract class PatchRequestModelBase : RequestModelBase {
public Dictionary<string, PatchOperation> Operations = new Dictionary<string, PatchOperation>();
public Dictionary<string, PatchOperation>? Operations { get; set; }
private bool HasNonNullPatchField => GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(prop => prop.Name != nameof(Operations))
.Any(prop => prop.GetValue(this) != null);
public bool TryGetOperation(string propertyName, out PatchOperation operation) {
return Operations.TryGetValue(propertyName, out operation);
public bool TryGetOperation(string propertyName, [NotNullWhen(true)] out PatchOperation? operation) {
if (Operations == null) {
operation = null;
return false;
}
if (Operations.TryGetValue(propertyName, out var tempOperation)) {
operation = tempOperation;
return true;
}
else {
operation = null;
return false;
}
}
public override IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
@ -24,6 +37,7 @@ public abstract class PatchRequestModelBase : RequestModelBase {
yield return new ValidationResult("At least one patch field must be provided", new string[] { "PatchField" });
}
if (Operations != null) {
foreach (var operation in Operations) {
if (!Enum.IsDefined(typeof(PatchOperation), operation.Value)) {
yield return new ValidationResult($"Invalid patch operation '{operation.Value}' for property '{operation.Key}'", new string[] { operation.Key });
@ -31,3 +45,4 @@ public abstract class PatchRequestModelBase : RequestModelBase {
}
}
}
}

View File

@ -8,7 +8,7 @@
<!-- NuGet package metadata -->
<PackageId>MaksIT.Core</PackageId>
<Version>1.2.5</Version>
<Version>1.2.6</Version>
<Authors>Maksym Sadovnychyy</Authors>
<Company>MAKS-IT</Company>
<Product>MaksIT.Core</Product>