using ModelTools.Enums;
using System;
using System.Collections.Generic;
namespace ModelTools.Models
{
///
/// Результат любой операции с сущностью
///
public class OperationResultModel
{
///
/// Успешность операции (количество ошибок = 0)
///
public bool IsSucceeded => Errors.Count == 0;
///
/// Статус операции
///
public ResultServiceStatusCode StatusCode { get; set; }
///
/// Спсиок ошибок
///
public List<(string Title, string Message)> Errors { get; private set; }
///
/// Объект, получаемый по результатам операции
///
public object Result { get; private set; }
///
/// Конструктор по умолчанию
///
public OperationResultModel()
{
Errors = new List<(string Title, string Message)>();
StatusCode = ResultServiceStatusCode.Success;
}
///
/// Успешно
///
///
///
public static OperationResultModel Success(object obj)
{
return new OperationResultModel
{
Result = obj,
Errors = new List<(string Title, string Message)>(),
StatusCode = ResultServiceStatusCode.Success
};
}
///
/// Добавление простой ошибки
///
///
///
///
public static OperationResultModel Error(string key, string value) => Error(key, value, ResultServiceStatusCode.Error);
///
/// Добавление простой ошибки со сменой статуса
///
///
///
///
///
public static OperationResultModel Error(string key, string error, ResultServiceStatusCode statusCode)
{
var model = new OperationResultModel();
model.Errors.Add((key, error));
model.StatusCode = statusCode;
return model;
}
///
/// Добавление ошибки
///
///
///
public static OperationResultModel Error(Exception error) => Error(error, ResultServiceStatusCode.Error);
///
/// Добавление ошибки
///
///
///
///
public static OperationResultModel Error(Exception error, ResultServiceStatusCode statusCode) => Error("Ошибка", error, statusCode);
///
/// Добавление ошибки (включая вложеннные)
///
///
///
///
///
public static OperationResultModel Error(string key, Exception error, ResultServiceStatusCode statusCode)
{
var model = new OperationResultModel();
model.Errors.Add((key, error.Message));
while (error.InnerException != null)
{
error = error.InnerException;
model.Errors.Add(("Inner error:", error.Message));
}
model.StatusCode = statusCode;
return model;
}
}
}