2 Commits

Author SHA1 Message Date
9d48f53ebe в сущности подобавлял 2025-05-29 07:03:48 +04:00
64e980b1c5 попытка 1 2025-05-29 06:03:27 +04:00
18 changed files with 589 additions and 282 deletions

View File

@@ -17,6 +17,7 @@ internal class IngredientDataModel(string id, string NameIngredients, string siz
public string SizeInit { get; private set; } = sizeInit;
public double InitPrice { get; private set; } = initPrice;
public IngredientDataModel(): this(string.Empty, string.Empty, string.Empty, 0) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (Id.IsEmpty())

View File

@@ -15,6 +15,8 @@ internal class IngredientHistoryDataModel(string productId, double oldPrice) : I
public string IngredienId { get; private set; } = productId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public IngredientHistoryDataModel():this(string.Empty, 0) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (IngredienId.IsEmpty())

View File

@@ -12,6 +12,7 @@ using System.Threading.Tasks;
using System.Xml;
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.Mapper;
namespace SladkieBulkiContrakts.DataModels;
@@ -23,21 +24,13 @@ internal class PostDataModel(string postId, string postName, PostType postType,
public PostType PostType { get; private set; } = postType;
[AlternativeName("ConfigurationJson")]
[AlternativeName("Configuration")]
[PostProcessing(MappingCallMethodName = "ParseJson")]
public PostConfiguration ConfigurationModel { get; private set; } = configuration;
public PostDataModel() : this(string.Empty, string.Empty, PostType.None, null) { }
public PostDataModel(string postId, string postName, PostType postType, string configurationJson) : this(postId, postName, postType, (PostConfiguration)null)
{
var obj = JToken.Parse(configurationJson);
if (obj is not null)
{
ConfigurationModel = obj.Value<string>("Type") switch
{
nameof(ManufacturerPostConfiguration) => JsonConvert.DeserializeObject<ManufacturerPostConfiguration>(configurationJson)!,
nameof(PackerPostConfiguration) => JsonConvert.DeserializeObject<PackerPostConfiguration>(configurationJson)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(configurationJson)!,
};
}
}
public void Validate(IStringLocalizer<Messages> localizer)
{
@@ -59,4 +52,18 @@ internal class PostDataModel(string postId, string postName, PostType postType,
if (ConfigurationModel!.Rate <= 0)
throw new ValidationException(string.Format(localizer["ValidationExceptionMessageLessOrEqualZero"], "Rate"));
}
private PostConfiguration? ParseJson(string json)
{
var obj = JToken.Parse(json);
if (obj is not null)
{
return obj.Value<string>("Type") switch
{
nameof(ManufacturerPostConfiguration) => JsonConvert.DeserializeObject<ManufacturerPostConfiguration>(json)!,
nameof(PackerPostConfiguration) => JsonConvert.DeserializeObject<PackerPostConfiguration>(json)!,
_ => JsonConvert.DeserializeObject<PostConfiguration>(json)!,
};
}
return null;
}
}

View File

@@ -3,6 +3,7 @@ using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Exceptions;
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.Mapper;
using SladkieBulkiContrakts.Resources;
using System.Collections.Generic;
using System.Diagnostics;
@@ -17,14 +18,14 @@ internal class ProductDataModel : IValidation
public string Name { get; private set; }
public string Description { get; private set; }
public ProductType ProductType { get; private set; }
[AlternativeName("ProductIngredients")]
public List<ProductIngredientDataModel> Ingredients { get; private set; }
public double UnitPrice { get; private set; }
public bool IsDeleted { get; private set; }
public ProductDataModel()
{
Ingredients = new List<ProductIngredientDataModel>();
}
public ProductDataModel(): this(string.Empty, string.Empty, string.Empty, ProductType.None, new List<ProductIngredientDataModel>(), 0, false) { }
public ProductDataModel(string id, string name, string description, ProductType productType, List<ProductIngredientDataModel> ingredients, double unitPrice, bool isDeleted)
{

View File

@@ -15,6 +15,8 @@ internal class ProductHistoryDataModel(string productId, double oldPrice): IVali
public string ProductId { get; private set; } = productId;
public double OldPrice { get; private set; } = oldPrice;
public DateTime ChangeDate { get; private set; } = DateTime.UtcNow;
public ProductHistoryDataModel(): this(string.Empty, 0) { }
public void Validate(IStringLocalizer<Messages> localizer)
{

View File

@@ -17,6 +17,8 @@ internal class ProductIngredientDataModel(string productId, string ingredientId,
public string ProductId { get; private set; } = productId;
public string IngredientId { get; private set; } = ingredientId;
public int Count { get; private set; } = count;
public ProductIngredientDataModel(): this(string.Empty, string.Empty, 1) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (ProductId.IsEmpty())

View File

@@ -2,15 +2,18 @@
using SladkieBulkiContrakts.Extensions;
using SladkieBulkiContrakts.Infrastructure;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.Mapper;
internal class ProductionDataModel(string id, DateTime productionDate, int count, double sum, string workerId, string productId) : IValidation
{
public string Id { get; private set; } = id;
[IgnoreValue]
public DateTime ProductionDate { get; private set; } = productionDate.ToUniversalTime();
public int Count { get; private set; } = count;
public double Sum { get; private set; } = sum;
public string WorkerId { get; private set; } = workerId;
public string ProductId { get; private set; } = productId;
public ProductionDataModel(): this(string.Empty, DateTime.UtcNow, 1, 10, string.Empty, string.Empty) { }
public void Validate(IStringLocalizer<Messages> localizer)
{

View File

@@ -12,6 +12,7 @@ namespace SladkieBulkiContrakts.DataModels;
internal class SalaryDataModel(string workerId, DateTime salaryDate, double workerSalary) : IValidation
{
[SourceFromMember(SourcePropertyName = "Worker")]
private readonly WorkerDataModel? _worker;
public string WorkerId { get; private set; } = workerId;
public DateTime SalaryDate { get; private set; } = salaryDate.ToUniversalTime();
@@ -21,6 +22,9 @@ internal class SalaryDataModel(string workerId, DateTime salaryDate, double work
{
_worker = worker;
}
public SalaryDataModel(): this(string.Empty, DateTime.UtcNow, 100) { }
public void Validate(IStringLocalizer<Messages> localizer)
{
if (WorkerId.IsEmpty())

View File

@@ -12,11 +12,13 @@ using System.Numerics;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.Infrastructure.PostConfigurations;
namespace SladkieBulkiContrakts.DataModels;
internal class WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, string email) : IValidation
{
[SourceFromMember(SourcePropertyName = "Post")]
private readonly PostDataModel? _post;
public string Id { get; private set; } = id;
public string FIO { get; private set; } = fio;
@@ -25,13 +27,13 @@ internal class WorkerDataModel(string id, string fio, string postId, DateTime bi
public DateTime EmploymentDate { get; private set; } = employmentDate.ToUniversalTime();
public bool IsDeleted { get; private set; } = isDeleted;
public string Email { get; private set; } = email;
public PostConfiguration? PostConfiguration => _post?.ConfigurationModel ?? null;
public string PostName => _post?.PostName ?? string.Empty;
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, bool isDeleted, string email, PostDataModel post) : this(id, fio, postId, birthDate, employmentDate, isDeleted, email)
{
_post = post;
}
public WorkerDataModel() : this(string.Empty, string.Empty, string.Empty, DateTime.MinValue, DateTime.MinValue, false, string.Empty) { }
public WorkerDataModel(string id, string fio, string postId, DateTime birthDate, DateTime employmentDate, string email) : this(id, fio, postId, birthDate, employmentDate, false, email) { }
public void Validate(IStringLocalizer<Messages> localizer)

View File

@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Mapper;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
class AlternativeNameAttribute(string alternativeName) : Attribute
{
public string AlternativeName { get; set; } = alternativeName;
}

View File

@@ -0,0 +1,205 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Mapper;
internal static class CustomMapper
{
public static To MapObject<To>(object obj, To newObject)
{
ArgumentNullException.ThrowIfNull(obj);
ArgumentNullException.ThrowIfNull(newObject);
var typeFrom = obj.GetType();
var typeTo = newObject.GetType();
var propertiesFrom = typeFrom.GetProperties().Where(x => x.CanRead).ToArray();
foreach (var property in typeTo.GetProperties().Where(x => x.CanWrite))
{
//ignore
var propertyFrom = TryGetPropertyFrom(property, propertiesFrom);
if (propertyFrom is null)
{
FindAndMapDefaultValue(property, newObject);
continue;
}
var fromValue = propertyFrom.GetValue(obj);
var postProcessingAttribute = property.GetCustomAttribute<PostProcessingAttribute>();
if (postProcessingAttribute is not null)
{
var value = PostProcessing(fromValue, postProcessingAttribute, newObject);
if (value is not null)
{
property.SetValue(newObject, value);
}
continue;
}
if (propertyFrom.PropertyType.IsGenericType && propertyFrom.PropertyType.Name.StartsWith("List") && fromValue is not null)
{
fromValue = MapListOfObjects(property, fromValue);
}
if (fromValue is not null)
{
// Enum -> string
if (property.PropertyType == typeof(string) && propertyFrom.PropertyType.IsEnum)
{
property.SetValue(newObject, fromValue.ToString());
}
// string -> Enum
else if (property.PropertyType.IsEnum && propertyFrom.PropertyType == typeof(string))
{
if (Enum.TryParse(property.PropertyType, fromValue.ToString(), out var enumValue))
{
property.SetValue(newObject, enumValue);
}
}
// int -> Enum
else if (property.PropertyType.IsEnum && propertyFrom.PropertyType == typeof(int))
{
property.SetValue(newObject, Enum.ToObject(property.PropertyType, fromValue));
}
// Enum -> int
else if (property.PropertyType == typeof(int) && propertyFrom.PropertyType.IsEnum)
{
property.SetValue(newObject, (int)fromValue);
}
// Чистое совпадение типов
else if (property.PropertyType.IsAssignableFrom(propertyFrom.PropertyType))
{
property.SetValue(newObject, fromValue);
}
// Попытка привести через Convert.ChangeType
else
{
try
{
var converted = Convert.ChangeType(fromValue, property.PropertyType);
property.SetValue(newObject, converted);
}
catch
{
// Последняя попытка - через ToString()
property.SetValue(newObject, fromValue.ToString());
}
}
}
}
// fields
var classPostProcessing = typeTo.GetCustomAttribute<PostProcessingAttribute>();
if (classPostProcessing is not null && classPostProcessing.MappingCallMethodName is not null)
{
var methodInfo = typeTo.GetMethod(classPostProcessing.MappingCallMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo?.Invoke(newObject, []);
}
return newObject;
}
public static To MapObject<To>(object obj) => MapObject(obj, Activator.CreateInstance<To>()!);
public static To? MapObjectWithNull<To>(object? obj) => obj is null ? default : MapObject(obj, Activator.CreateInstance<To>());
private static PropertyInfo? TryGetPropertyFrom(PropertyInfo propertyTo, PropertyInfo[] propertiesFrom)
{
var customAttribute = propertyTo.GetCustomAttributes<AlternativeNameAttribute>()?
.ToArray()
.FirstOrDefault(x => propertiesFrom.Any(y => y.Name == x.AlternativeName));
if (customAttribute is not null)
{
return propertiesFrom.FirstOrDefault(x => x.Name == customAttribute.AlternativeName);
}
return propertiesFrom.FirstOrDefault(x => x.Name == propertyTo.Name);
}
private static object? PostProcessing<T>(object? value, PostProcessingAttribute postProcessingAttribute, T newObject)
{
if (value is null || newObject is null)
{
return null;
}
if (!string.IsNullOrEmpty(postProcessingAttribute.MappingCallMethodName))
{
var methodInfo =
newObject.GetType().GetMethod(postProcessingAttribute.MappingCallMethodName, BindingFlags.NonPublic | BindingFlags.Instance);
if (methodInfo is not null)
{
return methodInfo.Invoke(newObject, [value]);
}
}
else if (postProcessingAttribute.ActionType != PostProcessingType.None)
{
switch (postProcessingAttribute.ActionType)
{
case PostProcessingType.ToUniversalTime:
return ToUniversalTime(value);
case PostProcessingType.ToLocalTime:
return ToLocalTime(value);
}
}
return null;
}
private static object? ToLocalTime(object? obj)
{
if (obj is DateTime date)
return date.ToLocalTime();
return obj;
}
private static object? ToUniversalTime(object? obj)
{
if (obj is DateTime date)
return date.ToUniversalTime();
return obj;
}
private static void FindAndMapDefaultValue<T>(PropertyInfo property, T newObject)
{
var defaultValueAttribute = property.GetCustomAttribute<DefaultValueAttribute>();
if (defaultValueAttribute is null)
{
return;
}
if (defaultValueAttribute.DefaultValue is not null)
{
property.SetValue(newObject, defaultValueAttribute.DefaultValue);
return;
}
var value = defaultValueAttribute.FuncName switch
{
"UtcNow" => DateTime.UtcNow,
_ => (object?)null,
};
if (value is not null)
{
property.SetValue(newObject, value);
}
}
private static object? MapListOfObjects(PropertyInfo propertyTo, object list)
{
var listResult = Activator.CreateInstance(propertyTo.PropertyType);
foreach (var elem in (IEnumerable)list)
{
var newElem = MapObject(elem, Activator.CreateInstance(propertyTo.PropertyType.GenericTypeArguments[0])!);
if (newElem is not null)
{
propertyTo.PropertyType.GetMethod("Add")!.Invoke(listResult, [newElem]);
}
}
return listResult;
}
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Mapper;
[AttributeUsage(AttributeTargets.Property)]
class DefaultValueAttribute : Attribute
{
public object? DefaultValue { get; set; }
public string? FuncName { get; set; }
}

View File

@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Mapper;
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Class)]
class PostProcessingAttribute : Attribute
{
public string? MappingCallMethodName { get; set; }
public PostProcessingType ActionType { get; set; } = PostProcessingType.None;
}

View File

@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SladkieBulkiContrakts.Mapper;
enum PostProcessingType
{
None = -1,
ToUniversalTime = 1,
ToLocalTime = 2
}

View File

@@ -1,4 +1,8 @@
namespace SladkieBulkiContrakts.ViewModels;
using SladkieBulkiContrakts.Infrastructure.PostConfigurations;
using SladkieBulkiContrakts.Mapper;
using System.Text.Json;
namespace SladkieBulkiContrakts.ViewModels;
public class PostViewModel
{
@@ -8,5 +12,9 @@ public class PostViewModel
public required string PostType { get; set; }
[AlternativeName("ConfigurationModel")]
[PostProcessing(MappingCallMethodName = "ParseConfiguration")]
public required string Configuration { get; set; }
private string ParseConfiguration(PostConfiguration model) =>
JsonSerializer.Serialize(model, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });
}

View File

@@ -1,5 +1,6 @@
using SladkieBulkiContrakts.Enums;
using SladkieBulkiContrakts.Infrastructure.PostConfigurations;
using SladkieBulkiContrakts.Mapper;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -14,7 +15,12 @@ internal class Post
public required string PostId { get; set; }
public required string PostName { get; set; }
public PostType PostType { get; set; }
[AlternativeName("ConfigurationModel")]
public required PostConfiguration Configuration { get; set; }
[DefaultValue(DefaultValue = true)]
public bool IsActual { get; set; }
[DefaultValue(FuncName = "UtcNow")]
public DateTime ChangeDate { get; set; }
}

View File

@@ -8,6 +8,7 @@ using SladkieBulkiContrakts.ViewModels;
using SladkieBulkiContrakts.AdapterContracts;
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.Mapper;
namespace SladkieBulkiWedApi.Adapters;
@@ -15,19 +16,15 @@ internal class IngredientAdapter : IIngredientAdapter
{
private readonly IIngredientBusinessLogicContract _ingredientBusinessLogicContract;
private readonly ILogger _logger;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
public IngredientAdapter(IIngredientBusinessLogicContract ingredientBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<IngredientAdapter> logger)
public IngredientAdapter(
IIngredientBusinessLogicContract ingredientBusinessLogicContract,
IStringLocalizer<Messages> localizer,
ILogger<IngredientAdapter> logger)
{
_ingredientBusinessLogicContract = ingredientBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<IngredientBindingModel, IngredientDataModel>();
cfg.CreateMap<IngredientDataModel, IngredientViewModel>();
});
_mapper = new Mapper(config);
_localizer = localizer;
}
@@ -37,14 +34,16 @@ internal class IngredientAdapter : IIngredientAdapter
{
return IngredientOperationResponse.OK(
_ingredientBusinessLogicContract.GetAllIngredients()
.Select(x => _mapper.Map<IngredientViewModel>(x))
.Select(x => CustomMapper.MapObject<IngredientViewModel>(x))
.ToList()
);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return IngredientOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return IngredientOperationResponse.InternalServerError(
string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException?.Message)
);
}
catch (Exception ex)
{
@@ -53,7 +52,6 @@ internal class IngredientAdapter : IIngredientAdapter
}
}
public IngredientOperationResponse GetElement(string data)
{
try
@@ -65,7 +63,7 @@ internal class IngredientAdapter : IIngredientAdapter
model = _ingredientBusinessLogicContract.GetIngredientByName(data);
return IngredientOperationResponse.OK(
_mapper.Map<IngredientViewModel>(model)
CustomMapper.MapObject<IngredientViewModel>(model)
);
}
catch (ArgumentNullException ex)
@@ -76,17 +74,23 @@ internal class IngredientAdapter : IIngredientAdapter
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return IngredientOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
return IngredientOperationResponse.NotFound(
string.Format(_localizer["AdapterMessageElementNotFoundException"], data)
);
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], data));
return IngredientOperationResponse.BadRequest(
string.Format(_localizer["AdapterMessageElementDeletedException"], data)
);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return IngredientOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return IngredientOperationResponse.InternalServerError(
string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException?.Message)
);
}
catch (Exception ex)
{
@@ -99,7 +103,9 @@ internal class IngredientAdapter : IIngredientAdapter
{
try
{
_ingredientBusinessLogicContract.InsertIngredient(_mapper.Map<IngredientDataModel>(ingredientModel));
_ingredientBusinessLogicContract.InsertIngredient(
CustomMapper.MapObject<IngredientDataModel>(ingredientModel)
);
return IngredientOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
@@ -110,7 +116,9 @@ internal class IngredientAdapter : IIngredientAdapter
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
return IngredientOperationResponse.BadRequest(
string.Format(_localizer["AdapterMessageValidationException"], ex.Message)
);
}
catch (ElementExistsException ex)
{
@@ -120,7 +128,9 @@ internal class IngredientAdapter : IIngredientAdapter
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return IngredientOperationResponse.BadRequest(
string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException?.Message)
);
}
catch (Exception ex)
{
@@ -133,7 +143,9 @@ internal class IngredientAdapter : IIngredientAdapter
{
try
{
_ingredientBusinessLogicContract.UpdateIngredient(_mapper.Map<IngredientDataModel>(ingredientModel));
_ingredientBusinessLogicContract.UpdateIngredient(
CustomMapper.MapObject<IngredientDataModel>(ingredientModel)
);
return IngredientOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
@@ -144,12 +156,16 @@ internal class IngredientAdapter : IIngredientAdapter
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
return IngredientOperationResponse.BadRequest(
string.Format(_localizer["AdapterMessageValidationException"], ex.Message)
);
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], ingredientModel.Id));
return IngredientOperationResponse.BadRequest(
string.Format(_localizer["AdapterMessageElementNotFoundException"], ingredientModel.Id)
);
}
catch (ElementExistsException ex)
{
@@ -159,12 +175,16 @@ internal class IngredientAdapter : IIngredientAdapter
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], ingredientModel.Id));
return IngredientOperationResponse.BadRequest(
string.Format(_localizer["AdapterMessageElementDeletedException"], ingredientModel.Id)
);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return IngredientOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
return IngredientOperationResponse.BadRequest(
string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException?.Message)
);
}
catch (Exception ex)
{
@@ -172,5 +192,4 @@ internal class IngredientAdapter : IIngredientAdapter
return IngredientOperationResponse.InternalServerError(ex.Message);
}
}
}

View File

@@ -9,261 +9,247 @@ using SladkieBulkiContrakts.AdapterContracts;
using System.Text.Json;
using Microsoft.Extensions.Localization;
using SladkieBulkiContrakts.Resources;
using SladkieBulkiContrakts.Mapper;
namespace SladkieBulkiWedApi.Adapters;
internal class PostAdapter : IPostAdapter
internal class PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<PostAdapter> logger) : IPostAdapter
{
private readonly IPostBusinessLogicContract _postBusinessLogicContract;
private readonly IPostBusinessLogicContract _postBusinessLogicContract = postBusinessLogicContract;
private readonly ILogger _logger;
private readonly IStringLocalizer<Messages> _localizer = localizer;
private readonly Mapper _mapper;
private readonly IStringLocalizer<Messages> _localizer;
private readonly ILogger _logger = logger;
private readonly JsonSerializerOptions JsonSerializerOptions = new() { PropertyNameCaseInsensitive = true };
public PostAdapter(IPostBusinessLogicContract postBusinessLogicContract, IStringLocalizer<Messages> localizer, ILogger<PostAdapter> logger)
public PostOperationResponse GetList()
{
_postBusinessLogicContract = postBusinessLogicContract;
_logger = logger;
var config = new MapperConfiguration(cfg =>
try
{
cfg.CreateMap<PostBindingModel, PostDataModel>();
cfg.CreateMap<PostDataModel, PostViewModel>()
.ForMember(x => x.Configuration, x => x.MapFrom(src => JsonSerializer.Serialize(src.ConfigurationModel, JsonSerializerOptions)));
});
_mapper = new Mapper(config);
_localizer = localizer;
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => CustomMapper.MapObject<PostViewModel>(x))]);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
public PostOperationResponse GetList()
{
try
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllPosts().Select(x => _mapper.Map<PostViewModel>(x))]);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
public PostOperationResponse GetHistory(string id)
{
try
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => _mapper.Map<PostViewModel>(x))]);
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
public PostOperationResponse GetHistory(string id)
{
try
{
return PostOperationResponse.OK([.. _postBusinessLogicContract.GetAllDataOfPost(id).Select(x => CustomMapper.MapObject<PostViewModel>(x))]);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
public PostOperationResponse GetElement(string data)
{
try
{
return PostOperationResponse.OK(_mapper.Map<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], data));
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
public PostOperationResponse RegisterPost(PostBindingModel postModel)
{
try
{
_postBusinessLogicContract.InsertPost(_mapper.Map<PostDataModel>(postModel));
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementExistsException ex)
{
_logger.LogError(ex, "ElementExistsException");
return PostOperationResponse.BadRequest(ex.Message);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
public PostOperationResponse ChangePostInfo(PostBindingModel postModel)
{
try
{
_postBusinessLogicContract.UpdatePost(_mapper.Map<PostDataModel>(postModel));
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], postModel.Id));
}
catch (ElementExistsException ex)
{
_logger.LogError(ex, "ElementExistsException");
return PostOperationResponse.BadRequest(ex.Message);
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], postModel.Id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
public PostOperationResponse RemovePost(string id)
{
try
{
_postBusinessLogicContract.DeletePost(id);
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
public PostOperationResponse RestorePost(string id)
{
try
{
_postBusinessLogicContract.RestorePost(id);
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
public PostOperationResponse GetElement(string data)
{
try
{
return PostOperationResponse.OK(CustomMapper.MapObject<PostViewModel>(_postBusinessLogicContract.GetPostByData(data)));
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementNotFoundException"], data));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.NotFound(string.Format(_localizer["AdapterMessageElementDeletedException"], data));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
public PostOperationResponse RegisterPost(PostBindingModel postModel)
{
try
{
_postBusinessLogicContract.InsertPost(CustomMapper.MapObject<PostDataModel>(postModel));
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementExistsException ex)
{
_logger.LogError(ex, "ElementExistsException");
return PostOperationResponse.BadRequest(ex.Message);
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
public PostOperationResponse ChangePostInfo(PostBindingModel postModel)
{
try
{
_postBusinessLogicContract.UpdatePost(CustomMapper.MapObject<PostDataModel>(postModel));
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], postModel.Id));
}
catch (ElementExistsException ex)
{
_logger.LogError(ex, "ElementExistsException");
return PostOperationResponse.BadRequest(ex.Message);
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], postModel.Id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
public PostOperationResponse RemovePost(string id)
{
try
{
_postBusinessLogicContract.DeletePost(id);
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (ElementDeletedException ex)
{
_logger.LogError(ex, "ElementDeletedException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementDeletedException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
public PostOperationResponse RestorePost(string id)
{
try
{
_postBusinessLogicContract.RestorePost(id);
return PostOperationResponse.NoContent();
}
catch (ArgumentNullException ex)
{
_logger.LogError(ex, "ArgumentNullException");
return PostOperationResponse.BadRequest(_localizer["AdapterMessageEmptyDate"]);
}
catch (ValidationException ex)
{
_logger.LogError(ex, "ValidationException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageValidationException"], ex.Message));
}
catch (ElementNotFoundException ex)
{
_logger.LogError(ex, "ElementNotFoundException");
return PostOperationResponse.BadRequest(string.Format(_localizer["AdapterMessageElementNotFoundException"], id));
}
catch (StorageException ex)
{
_logger.LogError(ex, "StorageException");
return PostOperationResponse.InternalServerError(string.Format(_localizer["AdapterMessageStorageException"], ex.InnerException!.Message));
}
catch (Exception ex)
{
_logger.LogError(ex, "Exception");
return PostOperationResponse.InternalServerError(ex.Message);
}
}
}