forked from ddrilling/AsbCloudServer
Рефакторинг
1. Выпилил лишнюю логику 2. Прокинул IConfiguration в HelpPageService 3. Поправил миграции 4. Поправил тесты
This commit is contained in:
parent
9d2124673c
commit
a0720e9270
@ -2,6 +2,9 @@
|
||||
|
||||
namespace AsbCloudApp.Data;
|
||||
|
||||
/// <summary>
|
||||
/// Справка по страницам
|
||||
/// </summary>
|
||||
public class HelpPageDto : IId
|
||||
{
|
||||
/// <summary>
|
||||
|
@ -1,13 +1,11 @@
|
||||
using System;
|
||||
using AsbCloudApp.Exceptions.Interfaces;
|
||||
|
||||
namespace AsbCloudApp.Exceptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Argument validation fail Exception
|
||||
/// </summary>
|
||||
public class ArgumentInvalidException : Exception,
|
||||
IHasValidation
|
||||
public class ArgumentInvalidException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// название аргумента
|
||||
|
@ -1,47 +0,0 @@
|
||||
using System;
|
||||
using AsbCloudApp.Exceptions.Interfaces;
|
||||
|
||||
namespace AsbCloudApp.Exceptions;
|
||||
|
||||
/// <summary>
|
||||
/// Исключение для нескольких невалидных агрументов
|
||||
/// </summary>
|
||||
public class ArgumentsInvalidException : Exception,
|
||||
IHasValidation
|
||||
{
|
||||
/// <summary>
|
||||
/// Имена параметров
|
||||
/// </summary>
|
||||
public string[] ParamNames { get; } = Array.Empty<string>();
|
||||
|
||||
/// <summary>
|
||||
/// Контсруктор исключения
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
/// <param name="paramNames"></param>
|
||||
public ArgumentsInvalidException(string message,
|
||||
string[] paramNames)
|
||||
{
|
||||
ParamNames = paramNames;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// преобразование в объект валидации
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public object ToValidationErrorObject()
|
||||
=> MakeValidationError(ParamNames, Message);
|
||||
|
||||
/// <summary>
|
||||
/// фабрика объекта валидации
|
||||
/// </summary>
|
||||
/// <param name="paramName"></param>
|
||||
/// <param name="errors"></param>
|
||||
/// <returns></returns>
|
||||
public static object MakeValidationError(string[] paramNames, params string[] errors)
|
||||
=> new
|
||||
{
|
||||
names = paramNames,
|
||||
errors,
|
||||
};
|
||||
}
|
@ -1,13 +0,0 @@
|
||||
namespace AsbCloudApp.Exceptions.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Интерфейс конвертации исключений
|
||||
/// </summary>
|
||||
public interface IHasValidation
|
||||
{
|
||||
/// <summary>
|
||||
/// Интерфейс конвертации исключений
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
object ToValidationErrorObject();
|
||||
}
|
@ -20,15 +20,4 @@ public interface IHelpPageRepository : ICrudRepository<HelpPageDto>
|
||||
Task<HelpPageDto?> GetOrDefaultByUrlPageAndIdCategoryAsync(string urlPage,
|
||||
int idCategory,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Проверка на существование справки для определённой страницы в категории
|
||||
/// </summary>
|
||||
/// <param name="urlPage"></param>
|
||||
/// <param name="idCategory"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<bool> IsCheckHelpPageWithUrlPageAndIdCategoryAsync(string urlPage,
|
||||
int idCategory,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
|
@ -1,5 +1,4 @@
|
||||
using AsbCloudApp.Data;
|
||||
using System.IO;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
@ -11,7 +10,7 @@ namespace AsbCloudApp.Services;
|
||||
public interface IHelpPageService
|
||||
{
|
||||
/// <summary>
|
||||
/// Создание справки
|
||||
/// Метод обновления или обновления файла справки
|
||||
/// </summary>
|
||||
/// <param name="urlPage"></param>
|
||||
/// <param name="idCategory"></param>
|
||||
@ -19,52 +18,20 @@ public interface IHelpPageService
|
||||
/// <param name="fileStream"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<int> CreateAsync(string urlPage,
|
||||
int idCategory,
|
||||
string fileName,
|
||||
Stream fileStream,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Редактирование справки
|
||||
/// </summary>
|
||||
/// <param name="idCategory"></param>
|
||||
/// <param name="helpPage"></param>
|
||||
/// <param name="fileName"></param>
|
||||
/// <param name="fileStream"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task UpdateAsync(HelpPageDto helpPage,
|
||||
Task<int> AddOrUpdateAsync(string urlPage,
|
||||
int idCategory,
|
||||
string fileName,
|
||||
Stream fileStream,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Получение справки по url страницы и id категории
|
||||
/// Метод получения файла справки
|
||||
/// </summary>
|
||||
/// <param name="urlPage"></param>
|
||||
/// <param name="idCategory"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<HelpPageDto?> GetOrDefaultByUrlPageAndIdCategoryAsync(string urlPage,
|
||||
Task<(Stream stream, string fileName)> GetFileStreamAsync(string urlPage,
|
||||
int idCategory,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Получение справки по Id
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Task<HelpPageDto?> GetOrDefaultByIdAsync(int id,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Получение файла справки по Id
|
||||
/// </summary>
|
||||
/// <param name="helpPage"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
Stream GetFileStream(HelpPageDto helpPage);
|
||||
}
|
@ -2054,7 +2054,7 @@ namespace AsbCloudDb.Migrations
|
||||
{
|
||||
Id = 519,
|
||||
Description = "Разрешить создание справок по страницам",
|
||||
Name = "HelpPage.create"
|
||||
Name = "HelpPage.edit"
|
||||
});
|
||||
});
|
||||
|
||||
|
@ -11,7 +11,7 @@ namespace AsbCloudDb.Migrations
|
||||
migrationBuilder.InsertData(
|
||||
table: "t_permission",
|
||||
columns: new[] { "id", "description", "name" },
|
||||
values: new object[] { 519, "Разрешить создание справок по страницам", "HelpPage.create" });
|
||||
values: new object[] { 519, "Разрешить создание справок по страницам", "HelpPage.edit" });
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "t_relation_user_role_permission",
|
||||
|
@ -2052,7 +2052,7 @@ namespace AsbCloudDb.Migrations
|
||||
{
|
||||
Id = 519,
|
||||
Description = "Разрешить создание справок по страницам",
|
||||
Name = "HelpPage.create"
|
||||
Name = "HelpPage.edit"
|
||||
});
|
||||
});
|
||||
|
||||
|
@ -150,7 +150,7 @@
|
||||
new (){ Id = 517, Name="FaqStatistics.edit", Description="Разрешение редактировать вопрос"},
|
||||
new (){ Id = 518, Name="FaqStatistics.delete", Description="Разрешение удалять вопрос"},
|
||||
|
||||
new() { Id = 519, Name = "HelpPage.create", Description = "Разрешить создание справок по страницам" }
|
||||
new() { Id = 519, Name = "HelpPage.edit", Description = "Разрешить создание справок по страницам" }
|
||||
};
|
||||
}
|
||||
}
|
||||
|
@ -136,12 +136,7 @@ namespace AsbCloudInfrastructure
|
||||
services.AddTransient<ILimitingParameterService, LimitingParameterService>();
|
||||
services.AddTransient<IProcessMapReportMakerService, ProcessMapReportMakerService>();
|
||||
services.AddTransient<IProcessMapReportService, ProcessMapReportService>();
|
||||
services.AddTransient<IHelpPageService, HelpPageService>(serviceProvider =>
|
||||
new HelpPageService(
|
||||
serviceProvider.GetRequiredService<IHelpPageRepository>(),
|
||||
serviceProvider.GetRequiredService<IFileStorageRepository>(),
|
||||
configuration.GetSection("HelpPageOptions:DirectoryNameHelpPageFiles")
|
||||
.Get<string>()));
|
||||
services.AddTransient<IHelpPageService, HelpPageService>();
|
||||
|
||||
services.AddTransient<TrajectoryService>();
|
||||
|
||||
|
@ -31,13 +31,4 @@ public class HelpPageRepository : CrudRepositoryBase<HelpPageDto, HelpPage>,
|
||||
|
||||
return helpPage.Adapt<HelpPageDto>();
|
||||
}
|
||||
|
||||
public Task<bool> IsCheckHelpPageWithUrlPageAndIdCategoryAsync(string urlPage, int idCategory,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
return dbSet.AnyAsync(x =>
|
||||
x.UrlPage == urlPage &&
|
||||
x.IdCategory == idCategory,
|
||||
cancellationToken);
|
||||
}
|
||||
}
|
||||
|
@ -1,16 +1,16 @@
|
||||
using System;
|
||||
using AsbCloudApp.Data;
|
||||
using AsbCloudApp.Data;
|
||||
using AsbCloudApp.Repositories;
|
||||
using AsbCloudApp.Services;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using AsbCloudApp.Exceptions;
|
||||
|
||||
namespace AsbCloudInfrastructure.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Реализация сервиса справок страниц
|
||||
/// Реализация сервиса для справок по страницам
|
||||
/// </summary>
|
||||
public class HelpPageService : IHelpPageService
|
||||
{
|
||||
@ -23,21 +23,18 @@ public class HelpPageService : IHelpPageService
|
||||
/// </summary>
|
||||
/// <param name="helpPageRepository"></param>
|
||||
/// <param name="fileStorageRepository"></param>
|
||||
/// <param name="directoryNameHelpPageFiles"></param>
|
||||
/// <param name="configuration"></param>
|
||||
public HelpPageService(IHelpPageRepository helpPageRepository,
|
||||
IFileStorageRepository fileStorageRepository,
|
||||
string directoryNameHelpPageFiles)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(directoryNameHelpPageFiles))
|
||||
throw new ArgumentException("Value cannot be null or whitespace", nameof(this.directoryNameHelpPageFiles));
|
||||
|
||||
IConfiguration configuration)
|
||||
{
|
||||
this.helpPageRepository = helpPageRepository;
|
||||
this.fileStorageRepository = fileStorageRepository;
|
||||
this.directoryNameHelpPageFiles = directoryNameHelpPageFiles;
|
||||
directoryNameHelpPageFiles = configuration.GetValue<string>("DirectoryNameHelpPageFiles");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание справки страницы
|
||||
/// Метод обновления или обновления файла справки
|
||||
/// </summary>
|
||||
/// <param name="urlPage"></param>
|
||||
/// <param name="idCategory"></param>
|
||||
@ -45,20 +42,67 @@ public class HelpPageService : IHelpPageService
|
||||
/// <param name="fileStream"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task<int> CreateAsync(string urlPage,
|
||||
public async Task<int> AddOrUpdateAsync(string urlPage,
|
||||
int idCategory,
|
||||
string fileName,
|
||||
Stream fileStream,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var helpPage = await helpPageRepository.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
|
||||
idCategory,
|
||||
cancellationToken);
|
||||
|
||||
if(helpPage is not null)
|
||||
{
|
||||
await UpdateFileAsync(helpPage,
|
||||
idCategory,
|
||||
fileName,
|
||||
fileStream,
|
||||
cancellationToken);
|
||||
|
||||
return helpPage.Id;
|
||||
}
|
||||
|
||||
return await SaveFileAsync(urlPage,
|
||||
idCategory,
|
||||
fileName,
|
||||
fileStream,
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Метод получения файла справки
|
||||
/// </summary>
|
||||
/// <param name="urlPage"></param>
|
||||
/// <param name="idCategory"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="ArgumentInvalidException"></exception>
|
||||
public async Task<(Stream stream, string fileName)> GetFileStreamAsync(string urlPage,
|
||||
int idCategory,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var helpPage = await helpPageRepository.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
|
||||
idCategory,
|
||||
cancellationToken) ?? throw new ArgumentInvalidException("Справки не существует", nameof(idCategory));
|
||||
|
||||
string filePath = fileStorageRepository.GetFilePath(directoryNameHelpPageFiles,
|
||||
helpPage.IdCategory.ToString(),
|
||||
helpPage.Id,
|
||||
Path.GetExtension(helpPage.Name));
|
||||
|
||||
var fileStream = new FileStream(Path.GetFullPath(filePath), FileMode.Open);
|
||||
|
||||
return (fileStream, helpPage.Name);
|
||||
}
|
||||
|
||||
private async Task<int> SaveFileAsync(string urlPage,
|
||||
int idCategory,
|
||||
string fileName,
|
||||
Stream fileStream,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (await helpPageRepository.IsCheckHelpPageWithUrlPageAndIdCategoryAsync(urlPage,
|
||||
idCategory,
|
||||
cancellationToken))
|
||||
{
|
||||
throw new ArgumentsInvalidException("Справка с такой категории файла для данной страницы уже существует",
|
||||
new[] { nameof(urlPage), nameof(idCategory) });
|
||||
}
|
||||
|
||||
HelpPageDto helpPage = new()
|
||||
{
|
||||
UrlPage = urlPage,
|
||||
@ -79,16 +123,7 @@ public class HelpPageService : IHelpPageService
|
||||
return idFile;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Обновление справки страницы
|
||||
/// </summary>
|
||||
/// <param name="helpPage"></param>
|
||||
/// <param name="idCategory"></param>
|
||||
/// <param name="fileName"></param>
|
||||
/// <param name="fileStream"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public async Task UpdateAsync(HelpPageDto helpPage,
|
||||
private async Task UpdateFileAsync(HelpPageDto helpPage,
|
||||
int idCategory,
|
||||
string fileName,
|
||||
Stream fileStream,
|
||||
@ -115,47 +150,11 @@ public class HelpPageService : IHelpPageService
|
||||
cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение справки по url страницы и id категории
|
||||
/// </summary>
|
||||
/// <param name="urlPage"></param>
|
||||
/// <param name="idCategory"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public Task<HelpPageDto?> GetOrDefaultByUrlPageAndIdCategoryAsync(string urlPage,
|
||||
int idCategory,
|
||||
CancellationToken cancellationToken) =>
|
||||
helpPageRepository.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
|
||||
idCategory,
|
||||
cancellationToken);
|
||||
|
||||
public Task<HelpPageDto?> GetOrDefaultByIdAsync(int id, CancellationToken cancellationToken) =>
|
||||
helpPageRepository.GetOrDefaultAsync(id,
|
||||
cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Получение файлового потока для файла справки
|
||||
/// </summary>
|
||||
/// <param name="helpPage"></param>
|
||||
/// <param name="cancellationToken"></param>
|
||||
/// <returns></returns>
|
||||
public Stream GetFileStream(HelpPageDto helpPage)
|
||||
{
|
||||
string filePath = fileStorageRepository.GetFilePath(directoryNameHelpPageFiles,
|
||||
helpPage.IdCategory.ToString(),
|
||||
helpPage.Id,
|
||||
Path.GetExtension(helpPage.Name));;
|
||||
|
||||
var fileStream = new FileStream(Path.GetFullPath(filePath), FileMode.Open);
|
||||
|
||||
return fileStream;
|
||||
}
|
||||
|
||||
private async Task SaveFileAsync(int idCategory,
|
||||
string fileName,
|
||||
Stream fileStream,
|
||||
int fileId,
|
||||
CancellationToken cancellationToken = default)
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
string filePath = fileStorageRepository.MakeFilePath(directoryNameHelpPageFiles,
|
||||
idCategory.ToString(),
|
||||
|
@ -5,10 +5,10 @@ using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AsbCloudApp.Data;
|
||||
using AsbCloudApp.Exceptions;
|
||||
using AsbCloudApp.Repositories;
|
||||
using AsbCloudApp.Services;
|
||||
using AsbCloudInfrastructure.Services;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
@ -16,7 +16,9 @@ namespace AsbCloudWebApi.Tests.ServicesTests;
|
||||
|
||||
public class HelpPageServiceTest
|
||||
{
|
||||
private const string directoryNameHelpPageFiles = "helpPages";
|
||||
private static Dictionary<string, string> configSettings = new (){
|
||||
{"DirectoryNameHelpPageFiles", "helpPages"}
|
||||
};
|
||||
|
||||
private static List<HelpPageDto> HelpPages = new()
|
||||
{
|
||||
@ -45,7 +47,7 @@ public class HelpPageServiceTest
|
||||
UrlPage = "test2"
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
private readonly Mock<IHelpPageRepository> helpPageRepository = new();
|
||||
private readonly Mock<IFileStorageRepository> fileStorageRepository = new();
|
||||
|
||||
@ -53,21 +55,36 @@ public class HelpPageServiceTest
|
||||
|
||||
public HelpPageServiceTest()
|
||||
{
|
||||
IConfiguration configuration = new ConfigurationBuilder()
|
||||
.AddInMemoryCollection(configSettings)
|
||||
.Build();
|
||||
|
||||
helpPageService = new HelpPageService(helpPageRepository.Object,
|
||||
fileStorageRepository.Object,
|
||||
directoryNameHelpPageFiles);
|
||||
configuration);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_ShouldReturn_PositiveId()
|
||||
public async Task AddOrUpdateAsync_ShouldReturn_NewHelpPage()
|
||||
{
|
||||
//arrange
|
||||
int idHelpPage = new Random().Next(1, 100);
|
||||
string urlPage = "test";
|
||||
int idCategory = 20000;
|
||||
string fullName = "test.pdf";
|
||||
string fileName = "test.pdf";
|
||||
MemoryStream fileStream = new MemoryStream(Array.Empty<byte>());
|
||||
|
||||
helpPageRepository.Setup(x => x.GetOrDefaultByUrlPageAndIdCategoryAsync(It.IsAny<string>(),
|
||||
It.IsAny<int>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(() =>
|
||||
{
|
||||
var helpPage = HelpPages.FirstOrDefault(x =>
|
||||
x.UrlPage == urlPage &&
|
||||
x.IdCategory == idCategory);
|
||||
|
||||
return Task.FromResult(helpPage);
|
||||
});
|
||||
|
||||
helpPageRepository.Setup(x => x.InsertAsync(It.IsAny<HelpPageDto>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Returns(() => Task.FromResult(idHelpPage));
|
||||
@ -77,9 +94,9 @@ public class HelpPageServiceTest
|
||||
It.IsAny<CancellationToken>()));
|
||||
|
||||
//act
|
||||
int result = await helpPageService.CreateAsync(urlPage,
|
||||
int result = await helpPageService.AddOrUpdateAsync(urlPage,
|
||||
idCategory,
|
||||
fullName,
|
||||
fileName,
|
||||
fileStream,
|
||||
CancellationToken.None);
|
||||
|
||||
@ -87,110 +104,42 @@ public class HelpPageServiceTest
|
||||
Assert.True(result > 0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_ShouldReturn_ArgumentsInvalidException()
|
||||
{
|
||||
//arrange
|
||||
string urlPage = "test";
|
||||
int idCategory = 20000;
|
||||
string fullName = "test.pdf";
|
||||
MemoryStream fileStream = new MemoryStream(Array.Empty<byte>());
|
||||
bool isExistingHelpPage = true;
|
||||
|
||||
helpPageRepository.Setup(x => x.IsCheckHelpPageWithUrlPageAndIdCategoryAsync(It.IsAny<string>(),
|
||||
It.IsAny<int>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Returns(() => Task.FromResult(isExistingHelpPage));
|
||||
|
||||
//act
|
||||
Task Result () => helpPageService.CreateAsync(urlPage,
|
||||
idCategory,
|
||||
fullName,
|
||||
fileStream,
|
||||
CancellationToken.None);
|
||||
|
||||
//assert
|
||||
await Assert.ThrowsAsync<ArgumentsInvalidException>(Result);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UpdateAsync_ShouldReturn_UpdatedHelpPage()
|
||||
{
|
||||
//arrange
|
||||
HelpPageDto helpPage = new()
|
||||
{
|
||||
Id = 123,
|
||||
IdCategory = 134,
|
||||
UrlPage = "test",
|
||||
Name = "Справка.pdf",
|
||||
Size = 54000
|
||||
};
|
||||
|
||||
int newIdCategory = 451;
|
||||
string newFileName = "Новая справка.pdf";
|
||||
int idHelpPage = new Random().Next(1, 100);
|
||||
string urlPage = "test";
|
||||
int newIdCategory = 20000;
|
||||
string newFileName = "test.pdf";
|
||||
MemoryStream newFileStream = new MemoryStream(Array.Empty<byte>());
|
||||
|
||||
HelpPageDto existingHelpPage = HelpPages.First(x =>
|
||||
x.UrlPage == urlPage &&
|
||||
x.IdCategory == newIdCategory);
|
||||
|
||||
helpPageRepository.Setup(x => x.GetOrDefaultByUrlPageAndIdCategoryAsync(It.IsAny<string>(),
|
||||
It.IsAny<int>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(() => Task.FromResult(existingHelpPage)!);
|
||||
|
||||
helpPageRepository.Setup(x => x.InsertAsync(It.IsAny<HelpPageDto>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Returns(() => Task.FromResult(idHelpPage));
|
||||
|
||||
fileStorageRepository.Setup(x => x.SaveFileAsync(It.IsAny<string>(),
|
||||
It.IsAny<Stream>(),
|
||||
It.IsAny<CancellationToken>()));
|
||||
|
||||
//act
|
||||
await helpPageService.UpdateAsync(helpPage,
|
||||
await helpPageService.AddOrUpdateAsync(urlPage,
|
||||
newIdCategory,
|
||||
newFileName,
|
||||
newFileStream,
|
||||
CancellationToken.None);
|
||||
|
||||
//assert
|
||||
Assert.Equal(newFileName, helpPage.Name);
|
||||
Assert.Equal(newIdCategory, helpPage.IdCategory);
|
||||
Assert.Equal(newFileStream.Length, helpPage.Size);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(20000, "test")]
|
||||
[InlineData(20000, "test1")]
|
||||
public async Task GetOrDefaultByUrlPageAndIdCategoryAsync_ShouldReturn_HelpPageDto(int idCategory,
|
||||
string urlPage)
|
||||
{
|
||||
//arrange
|
||||
helpPageRepository.Setup(x => x.GetOrDefaultByUrlPageAndIdCategoryAsync(It.IsAny<string>(),
|
||||
It.IsAny<int>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(() =>
|
||||
{
|
||||
var helpPage = HelpPages.FirstOrDefault(x =>
|
||||
x.UrlPage == urlPage &&
|
||||
x.IdCategory == idCategory);
|
||||
|
||||
return Task.FromResult(helpPage);
|
||||
});
|
||||
|
||||
//act
|
||||
var result = await helpPageService.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
|
||||
idCategory,
|
||||
CancellationToken.None);
|
||||
|
||||
//assert
|
||||
Assert.NotNull(result);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(123)]
|
||||
[InlineData(178)]
|
||||
public async Task GetOrDefaultByIdAsync_ShouldReturn_HelpPageDto(int id)
|
||||
{
|
||||
//arrange
|
||||
helpPageRepository.Setup(x => x.GetOrDefaultAsync(It.IsAny<int>(),
|
||||
It.IsAny<CancellationToken>()))
|
||||
.Returns(() =>
|
||||
{
|
||||
var helpPage = HelpPages.FirstOrDefault(x =>
|
||||
x.Id == id);
|
||||
|
||||
return Task.FromResult(helpPage);
|
||||
});
|
||||
|
||||
//act
|
||||
var result = await helpPageService.GetOrDefaultByIdAsync(id,
|
||||
CancellationToken.None);
|
||||
|
||||
//assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(newFileName, existingHelpPage.Name);
|
||||
Assert.Equal(newIdCategory, existingHelpPage.IdCategory);
|
||||
Assert.Equal(newFileStream.Length, existingHelpPage.Size);
|
||||
}
|
||||
}
|
@ -5,9 +5,9 @@ using System.ComponentModel.DataAnnotations;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using AsbCloudApp.Data;
|
||||
using AsbCloudApp.Repositories;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using System.Net;
|
||||
|
||||
namespace AsbCloudWebApi.Controllers;
|
||||
|
||||
@ -30,50 +30,37 @@ public class HelpPageController : ControllerBase
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Создание файла справки
|
||||
/// Загрузка файла справки
|
||||
/// </summary>
|
||||
/// <param name="urlPage">Url страницы для которой предназначена эта справка</param>
|
||||
/// <param name="idCategory">Id катагории файла</param>
|
||||
/// <param name="file">Загружаемый файл</param>
|
||||
/// <returns>Id созданной справки</returns>
|
||||
/// <param name="urlPage">Url страницы</param>
|
||||
/// <param name="idCategory">Id категории файла</param>
|
||||
/// <param name="file">Файл справки</param>
|
||||
/// <param name="cancellationToken">Токен для отмены задачи</param>
|
||||
/// <returns></returns>
|
||||
[HttpPost]
|
||||
[Permission]
|
||||
[Route("saveFile")]
|
||||
[ProducesResponseType(typeof(int), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> CreateAsync(string urlPage,
|
||||
[Route("upload")]
|
||||
[ProducesResponseType(typeof(int), (int)HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> UploadAsync(string urlPage,
|
||||
int idCategory,
|
||||
[Required] IFormFile file)
|
||||
[Required] IFormFile file,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
int? idUser = User.GetUserId();
|
||||
|
||||
if(!idUser.HasValue)
|
||||
return Forbid();
|
||||
|
||||
if (!userRepository.HasPermission(idUser.Value, $"HelpPage.create"))
|
||||
if (!userRepository.HasPermission(idUser.Value, $"HelpPage.edit"))
|
||||
return Forbid();
|
||||
|
||||
var helpPage = await helpPageService.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
|
||||
idCategory,
|
||||
CancellationToken.None);
|
||||
|
||||
using var fileStream = file.OpenReadStream();
|
||||
|
||||
if (helpPage is not null)
|
||||
{
|
||||
await helpPageService.UpdateAsync(helpPage,
|
||||
idCategory,
|
||||
file.FileName,
|
||||
fileStream,
|
||||
CancellationToken.None);
|
||||
|
||||
return Ok(helpPage.Id);
|
||||
}
|
||||
|
||||
int helpPageId = await helpPageService.CreateAsync(urlPage,
|
||||
int helpPageId = await helpPageService.AddOrUpdateAsync(urlPage,
|
||||
idCategory,
|
||||
file.FileName,
|
||||
fileStream,
|
||||
CancellationToken.None);
|
||||
cancellationToken);
|
||||
|
||||
return Ok(helpPageId);
|
||||
}
|
||||
@ -81,45 +68,29 @@ public class HelpPageController : ControllerBase
|
||||
/// <summary>
|
||||
/// Получение файла справки
|
||||
/// </summary>
|
||||
/// <param name="id">Id справки</param>
|
||||
/// <returns>Файл</returns>
|
||||
/// <param name="urlPage">Url страницы</param>
|
||||
/// <param name="idCategory">Id категории файла</param>
|
||||
/// <param name="cancellationToken">Токен для отмены задачи</param>
|
||||
/// <returns></returns>
|
||||
[HttpGet]
|
||||
[Route("getById/{id}")]
|
||||
[ProducesResponseType(typeof(PhysicalFileResult), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> GetFileAsync(int id)
|
||||
[Route("get/{urlPage}/{idCategory}")]
|
||||
[ProducesResponseType(typeof(PhysicalFileResult), (int)HttpStatusCode.OK)]
|
||||
[ProducesResponseType(StatusCodes.Status204NoContent)]
|
||||
public async Task<IActionResult> GetFileAsync(string urlPage,
|
||||
int idCategory,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var helpPage = await helpPageService.GetOrDefaultByIdAsync(id,
|
||||
CancellationToken.None);
|
||||
var file = await helpPageService.GetFileStreamAsync(urlPage,
|
||||
idCategory,
|
||||
cancellationToken);
|
||||
|
||||
if (helpPage is null)
|
||||
return NotFound();
|
||||
|
||||
using var fileStream = helpPageService.GetFileStream(helpPage);
|
||||
using var fileStream = file.stream;
|
||||
|
||||
var memoryStream = new MemoryStream();
|
||||
await fileStream.CopyToAsync(memoryStream,
|
||||
CancellationToken.None);
|
||||
await fileStream.CopyToAsync(memoryStream,
|
||||
cancellationToken);
|
||||
memoryStream.Position = 0;
|
||||
|
||||
return File(memoryStream, "application/octet-stream", helpPage.Name);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Получение информации о справке
|
||||
/// </summary>
|
||||
/// <param name="urlPage">Url страницы</param>
|
||||
/// <param name="idCategory">Id категории</param>
|
||||
/// <returns>Dto справки</returns>
|
||||
[HttpGet]
|
||||
[Route("getByUrlPage/{urlPage}/{idCategory}")]
|
||||
[ProducesResponseType(typeof(HelpPageDto), (int)System.Net.HttpStatusCode.OK)]
|
||||
public async Task<IActionResult> GetByUrlPageAsync(string urlPage,
|
||||
int idCategory)
|
||||
{
|
||||
var helpPage = await helpPageService.GetOrDefaultByUrlPageAndIdCategoryAsync(urlPage,
|
||||
idCategory,
|
||||
CancellationToken.None);
|
||||
|
||||
return Ok(helpPage);
|
||||
return File(memoryStream, "application/octet-stream", file.fileName);
|
||||
}
|
||||
}
|
||||
|
@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Http;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using AsbCloudApp.Exceptions.Interfaces;
|
||||
|
||||
namespace AsbCloudWebApi.Middlewares
|
||||
{
|
||||
@ -31,15 +30,6 @@ namespace AsbCloudWebApi.Middlewares
|
||||
var body = MakeJsonBody(ex);
|
||||
await context.Response.WriteAsync(body);
|
||||
}
|
||||
catch (ArgumentsInvalidException ex)
|
||||
{
|
||||
Console.WriteLine($"ArgumentExceptions in {context.Request.Method}: {ex.Message}");
|
||||
context.Response.Clear();
|
||||
context.Response.StatusCode = 400;
|
||||
context.Response.ContentType = "application/json";
|
||||
var body = MakeJsonBody(ex);
|
||||
await context.Response.WriteAsync(body);
|
||||
}
|
||||
catch (ForbidException ex)
|
||||
{
|
||||
Console.WriteLine($"ForbidException in {context.Request.Method}: {ex.Message}");
|
||||
@ -59,8 +49,7 @@ namespace AsbCloudWebApi.Middlewares
|
||||
}
|
||||
}
|
||||
|
||||
private static string MakeJsonBody<TException>(TException ex)
|
||||
where TException: Exception, IHasValidation
|
||||
private static string MakeJsonBody(ArgumentInvalidException ex)
|
||||
{
|
||||
object error = ex.ToValidationErrorObject();
|
||||
var buffer = System.Text.Json.JsonSerializer.Serialize(error);
|
||||
|
@ -26,9 +26,7 @@
|
||||
"companyName": "ООО \"Цифровое бурение\"",
|
||||
"supportMail": "support@digitaldrilling.ru"
|
||||
},
|
||||
"HelpPageOptions": {
|
||||
"DirectoryNameHelpPageFiles": "helpPages"
|
||||
},
|
||||
"DirectoryNameHelpPageFiles": "helpPages",
|
||||
"Urls": "http://0.0.0.0:5000" //;https://0.0.0.0:5001" //,
|
||||
// See https man: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/endpoints?view=aspnetcore-6.0
|
||||
//"Kestrel": {
|
||||
|
Loading…
Reference in New Issue
Block a user