88 lines
2.4 KiB
C#
88 lines
2.4 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 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 T Value { get; }
|
|
|
|
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>(KeyValuePair<string, string> error)
|
|
{
|
|
var validationResults = new ModelResult<T>(false);
|
|
|
|
validationResults.AddModelError(error.Key, error.Value);
|
|
|
|
return validationResults;
|
|
}
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|