Files
laatzen/LaaProductionWeb/LaaProductionWeb.API/Models/ModelResult[T].cs
T
2023-05-03 09:27:04 +02:00

78 lines
2.1 KiB
C#

namespace LaaProductionWeb.API.Models
{
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Collections.Generic;
using System.Linq;
public class ModelResult<T>
{
private readonly T value;
private readonly Dictionary<string, string> errors;
private ModelResult(bool succeeded)
{
this.Succeeded = succeeded;
this.errors = new Dictionary<string, string>();
}
private ModelResult(T value)
{
this.Succeeded = true;
this.value = value;
}
public bool Succeeded { get; }
public IReadOnlyDictionary<string, string> ModelErrors
=> this.errors;
public void AddModelError(string key, string value)
{
if (key != null)
{
this.errors[key] = value;
}
}
public static implicit operator ModelResult<T>(T value)
=> new ModelResult<T>(value);
public static implicit operator ModelResult<T>(ModelStateDictionary modelState)
{
var validationResults = new ModelResult<T>(false);
if (modelState != null)
{
foreach (var entry in modelState)
{
var errorKey = entry.Key;
var errorValue = entry.Value;
if (errorValue.ValidationState == ModelValidationState.Invalid && errorValue.Errors.Any())
{
validationResults.AddModelError(errorKey, errorValue.Errors.First().ErrorMessage);
}
}
}
return validationResults;
}
public static implicit operator ActionResult(ModelResult<T> modelState)
{
if (modelState is null)
{
return new NotFoundResult();
}
else if (modelState.Succeeded)
{
return new OkObjectResult(modelState.value);
}
return new BadRequestObjectResult(modelState.errors);
}
}
}