PIbd-22-Ismailov_SUBD/BlogDataModels/BusinessLogic/NewsLogic.cs

108 lines
3.1 KiB
C#
Raw Normal View History

2023-05-18 21:34:36 +04:00
using BlogContracts.BindingModel;
using BlogContracts.BusinessLogicContracts;
using BlogContracts.SearchModels;
using BlogContracts.StorageContracts;
using BlogContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessLogic
{
public class NewsLogic : INewsLogic
{
private readonly INewsStorage _newsStorage;
public NewsLogic(INewsStorage newsStorage)
{
_newsStorage = newsStorage ?? throw new ArgumentNullException(nameof(newsStorage));
}
public bool Create(NewsBindingModel model)
{
CheckModel(model);
if (_newsStorage.Insert(model) == null)
{
return false;
}
return true;
}
public bool Delete(NewsBindingModel model)
{
CheckModel(model);
if (_newsStorage.Delete(model) == null)
{
return false;
}
return true;
}
public NewsViewModel? ReadElement(NewsSearchModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
var element = _newsStorage.GetElement(model);
if (element == null)
{
return null;
}
return element;
}
public List<NewsViewModel>? ReadList(NewsSearchModel? model)
{
var list = model == null ? _newsStorage.GetFullList() : _newsStorage.GetFilteredList(model);
if (list == null)
{
return null;
}
return list;
}
public bool Update(NewsBindingModel model)
{
CheckModel(model);
if (_newsStorage.Update(model) == null)
{
return false;
}
return true;
}
private void CheckModel(NewsBindingModel model)
{
if (model == null)
{
throw new ArgumentNullException(nameof(model));
}
if (string.IsNullOrEmpty(model.Title))
{
throw new ArgumentException("Отсутвует название",
nameof(model.Title));
}
if (string.IsNullOrEmpty(model.Text))
{
throw new ArgumentException("Отсутвует текст",
nameof(model.Text));
}
if (string.IsNullOrEmpty(model.UserId.ToString()))
{
throw new ArgumentException("Отсутвует автор",
nameof(model.UserId));
}
if (_newsStorage.GetElement(new NewsSearchModel
{
Title = model.Title,
UserId = model.UserId,
}) != null)
{
throw new InvalidOperationException("Такая новость уже существует");
}
}
}
}