72 lines
2.0 KiB
C#
72 lines
2.0 KiB
C#
namespace Prefab.Web.Client.Models.Shared;
|
|
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using FluentValidation;
|
|
|
|
public sealed class ResultProblem
|
|
{
|
|
public string? Title { get; init; }
|
|
|
|
public string? Detail { get; init; }
|
|
|
|
public int? StatusCode { get; init; }
|
|
|
|
public IReadOnlyDictionary<string, string[]>? Errors { get; init; }
|
|
|
|
public static ResultProblem FromValidation(ValidationException exception)
|
|
{
|
|
var errors = exception.Errors
|
|
.GroupBy(error => string.IsNullOrWhiteSpace(error.PropertyName) ? string.Empty : error.PropertyName)
|
|
.ToDictionary(
|
|
group => group.Key,
|
|
group => group.Select(error => error.ErrorMessage ?? string.Empty).ToArray());
|
|
|
|
return new ResultProblem
|
|
{
|
|
Title = "Validation failed.",
|
|
Detail = "Request did not satisfy validation rules.",
|
|
StatusCode = (int)HttpStatusCode.BadRequest,
|
|
Errors = errors
|
|
};
|
|
}
|
|
|
|
public static ResultProblem Unexpected(string title, Exception exception, HttpStatusCode statusCode = HttpStatusCode.InternalServerError) =>
|
|
new()
|
|
{
|
|
Title = title,
|
|
Detail = exception.Message,
|
|
StatusCode = (int)statusCode
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// Represents the outcome of an operation that produces a value of type <typeparamref name="T"/>.
|
|
/// </summary>
|
|
/// <typeparam name="T">The payload type returned when the operation succeeds.</typeparam>
|
|
public sealed class Result<T>
|
|
{
|
|
public Result()
|
|
{
|
|
}
|
|
|
|
public bool IsSuccess => Problem is null;
|
|
|
|
public ResultProblem? Problem { get; init; }
|
|
|
|
public int? StatusCode => Problem?.StatusCode;
|
|
|
|
public T? Value { get; init; }
|
|
|
|
public static Result<T> Success(T value) => new()
|
|
{
|
|
Value = value ?? throw new ArgumentNullException(nameof(value))
|
|
};
|
|
|
|
public static Result<T> Failure(ResultProblem problem) => new()
|
|
{
|
|
Problem = problem ?? throw new ArgumentNullException(nameof(problem))
|
|
};
|
|
}
|