diff --git a/README.md b/README.md index 59cc5ac..456096e 100644 --- a/README.md +++ b/README.md @@ -10,4 +10,11 @@ 2.1) Если упали пробуем сбилдить проект: dotnet build Api/Api.csproj 3) Применяем миграции: - dotnet ef database update --project Dal --startup-project Api --context UserDbContext \ No newline at end of file + dotnet ef database update --project Dal --startup-project Api --context UserDbContext + +Команды для миграций задач (TaskDbContext): +1) Миграция уже создана и лежит в Dal/Migrations/TaskMigrations + (если нужно её пересоздать: + dotnet ef migrations add CreateTasks --project Dal --startup-project Api --context TaskDbContext --output-dir Migrations/TaskMigrations) +2) Применяем миграции задач: + dotnet ef database update --project Dal --startup-project Api --context TaskDbContext \ No newline at end of file diff --git a/TaskHub/.gitattributes b/TaskHub/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/TaskHub/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/TaskHub/.gitignore b/TaskHub/.gitignore new file mode 100644 index 0000000..9491a2f --- /dev/null +++ b/TaskHub/.gitignore @@ -0,0 +1,363 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd \ No newline at end of file diff --git a/TaskHub/Api/Controllers/Tasks/Request/CreateTaskRequest.cs b/TaskHub/Api/Controllers/Tasks/Request/CreateTaskRequest.cs new file mode 100644 index 0000000..87844be --- /dev/null +++ b/TaskHub/Api/Controllers/Tasks/Request/CreateTaskRequest.cs @@ -0,0 +1,17 @@ +namespace Api.Controllers.Tasks.Request; + +/// +/// Запрос на создание задачи +/// +public record CreateTaskRequest +{ + /// + /// Название задачи + /// + public string? Title { get; init; } + + /// + /// Идентификатор пользователя, создавшего задачу + /// + public required Guid CreatedByUserId { get; init; } +} diff --git a/TaskHub/Api/Controllers/Tasks/Request/SetTaskTitleRequest.cs b/TaskHub/Api/Controllers/Tasks/Request/SetTaskTitleRequest.cs new file mode 100644 index 0000000..3f578aa --- /dev/null +++ b/TaskHub/Api/Controllers/Tasks/Request/SetTaskTitleRequest.cs @@ -0,0 +1,12 @@ +namespace Api.Controllers.Tasks.Request; + +/// +/// Запрос на изменение названия задачи +/// +public record SetTaskTitleRequest +{ + /// + /// Название задачи + /// + public string? Title { get; init; } +} diff --git a/TaskHub/Api/Controllers/Tasks/Response/TaskListResponse.cs b/TaskHub/Api/Controllers/Tasks/Response/TaskListResponse.cs new file mode 100644 index 0000000..9ed675a --- /dev/null +++ b/TaskHub/Api/Controllers/Tasks/Response/TaskListResponse.cs @@ -0,0 +1,21 @@ +namespace Api.Controllers.Tasks.Response; + +/// +/// Ответ со списком задач +/// +public record TaskListResponse +{ + /// + /// Список задач + /// + public IReadOnlyCollection TaskList { get; init; } + + /// + /// Создает ответ со списком задач + /// + /// Список задач + public TaskListResponse(IReadOnlyCollection taskList) + { + TaskList = taskList; + } +} diff --git a/TaskHub/Api/Controllers/Tasks/Response/TaskResponse.cs b/TaskHub/Api/Controllers/Tasks/Response/TaskResponse.cs new file mode 100644 index 0000000..f390910 --- /dev/null +++ b/TaskHub/Api/Controllers/Tasks/Response/TaskResponse.cs @@ -0,0 +1,38 @@ +namespace Api.Controllers.Tasks.Response; + +/// +/// Ответ с данными задачи +/// +public record TaskResponse +{ + /// + /// Идентификатор задачи + /// + public Guid Id { get; } + + /// + /// Название задачи + /// + public string? Title { get; } + + /// + /// Идентификатор пользователя, создавшего задачу + /// + public Guid CreatedByUserId { get; } + + /// + /// Дата и время создания задачи в UTC + /// + public DateTimeOffset CreatedUtc { get; } + + /// + /// Создает ответ с данными задачи + /// + public TaskResponse(Guid id, string? title, Guid createdByUserId, DateTimeOffset createdUtc) + { + Id = id; + Title = title; + CreatedByUserId = createdByUserId; + CreatedUtc = createdUtc; + } +} diff --git a/TaskHub/Api/Controllers/Tasks/TasksController.cs b/TaskHub/Api/Controllers/Tasks/TasksController.cs new file mode 100644 index 0000000..46f60b5 --- /dev/null +++ b/TaskHub/Api/Controllers/Tasks/TasksController.cs @@ -0,0 +1,125 @@ +using Api.Controllers.Tasks.Request; +using Api.Controllers.Tasks.Response; +using Api.ModelBinders; +using Logic.Tasks.Services.Interfaces; +using Microsoft.AspNetCore.Mvc; + +namespace Api.Controllers.Tasks; + +/// +/// Контроллер работы с задачами +/// +[ApiController] +[Route("tasks")] +public sealed class TasksController : ControllerBase +{ + /// + /// Сервис управления задачами + /// + private readonly ITaskService _taskService; + + public TasksController(ITaskService taskService) + { + _taskService = taskService; + } + + /// + /// Создать задачу + /// + /// Данные для создания задачи + /// Токен отмены + /// Созданная задача + [HttpPost] + public async Task> CreateTaskAsync( + [FromBody] CreateTaskRequest? request, + CancellationToken cancellationToken) + { + var task = await _taskService.CreateTaskAsync(request!.Title, request.CreatedByUserId, cancellationToken); + var response = new TaskResponse(task.Id, task.Title, task.CreatedByUserId, task.CreatedUtc); + return StatusCode(StatusCodes.Status201Created, response); + } + + /// + /// Получить все задачи + /// + /// Токен отмены + /// Список задач + [HttpGet] + public async Task> GetAllTasksAsync(CancellationToken cancellationToken) + { + var tasks = await _taskService.GetAllTasksAsync(cancellationToken); + + var responseList = tasks + .Select(x => new TaskResponse(x.Id, x.Title, x.CreatedByUserId, x.CreatedUtc)) + .ToList() + .AsReadOnly(); + + return Ok(new TaskListResponse(responseList)); + } + + /// + /// Получить задачу по идентификатору + /// + /// Идентификатор задачи + /// Токен отмены + /// Задача или 404, если задача не найдена + [HttpGet("{id}")] + public async Task> GetTaskByIdAsync([FromRouteTaskId] Guid id, CancellationToken cancellationToken) + { + var task = await _taskService.GetTaskByIdAsync(id, cancellationToken); + + if (task is null) + { + return NotFound(); + } + + return Ok(new TaskResponse(task.Id, task.Title, task.CreatedByUserId, task.CreatedUtc)); + } + + /// + /// Изменить название задачи + /// + /// Идентификатор задачи + /// Данные для изменения названия + /// Токен отмены + /// 204 при успехе + [HttpPut("{id}/title")] + public async Task SetTaskTitleAsync( + [FromRouteTaskId] Guid id, + [FromBody] SetTaskTitleRequest? request, + CancellationToken cancellationToken) + { + await _taskService.SetTaskTitleAsync(id, request!.Title, cancellationToken); + return NoContent(); + } + + /// + /// Удалить задачу по идентификатору + /// + /// Идентификатор задачи + /// Токен отмены + /// 204 при успехе или 404, если задача не найдена + [HttpDelete("{id}")] + public async Task DeleteTaskByIdAsync([FromRouteTaskId] Guid id, CancellationToken cancellationToken) + { + var deleted = await _taskService.DeleteTaskByIdAsync(id, cancellationToken); + if (deleted == false) + { + return NotFound(); + } + + return NoContent(); + } + + /// + /// Удалить все задачи + /// + /// Токен отмены + /// 204 при успехе + [HttpDelete] + public async Task DeleteAllTasksAsync(CancellationToken cancellationToken) + { + await _taskService.DeleteAllTasksAsync(cancellationToken); + return NoContent(); + } +} diff --git a/TaskHub/Api/DependencyInjection/DisposedService.cs b/TaskHub/Api/DependencyInjection/DisposedService.cs new file mode 100644 index 0000000..01ae2b2 --- /dev/null +++ b/TaskHub/Api/DependencyInjection/DisposedService.cs @@ -0,0 +1,17 @@ +namespace Api.DependencyInjection; + +public abstract class DisposedService : IHasInstanceId, IDisposable +{ + public Guid InstanceId { get; } = Guid.NewGuid(); + protected abstract string ServiceName { get; } + + protected DisposedService() + { + Console.WriteLine($"[CREATE] {ServiceName}: {InstanceId}"); + } + + public void Dispose() + { + Console.WriteLine($"[DISPOSE] {ServiceName}: {InstanceId}"); + } +} \ No newline at end of file diff --git a/TaskHub/Api/DependencyInjection/IHasInstanceId.cs b/TaskHub/Api/DependencyInjection/IHasInstanceId.cs new file mode 100644 index 0000000..00c05e1 --- /dev/null +++ b/TaskHub/Api/DependencyInjection/IHasInstanceId.cs @@ -0,0 +1,6 @@ +namespace Api.DependencyInjection; + +public interface IHasInstanceId +{ + Guid InstanceId { get; } +} \ No newline at end of file diff --git a/TaskHub/Api/DependencyInjection/LifetimeServices.cs b/TaskHub/Api/DependencyInjection/LifetimeServices.cs new file mode 100644 index 0000000..d72d489 --- /dev/null +++ b/TaskHub/Api/DependencyInjection/LifetimeServices.cs @@ -0,0 +1,42 @@ +namespace Api.DependencyInjection; + +// Интерфейсы +public interface ISingletonService1 : IHasInstanceId { } +public interface ISingletonService2 : IHasInstanceId { } +public interface IScopedService1 : IHasInstanceId { } +public interface IScopedService2 : IHasInstanceId { } +public interface ITransientService1 : IHasInstanceId { } +public interface ITransientService2 : IHasInstanceId { } + +// Реализации Singleton +public class SingletonService1 : DisposedService, ISingletonService1 +{ + protected override string ServiceName => nameof(SingletonService1); +} + +public class SingletonService2 : DisposedService, ISingletonService2 +{ + protected override string ServiceName => nameof(SingletonService2); +} + +// Реализации Scoped +public class ScopedService1 : DisposedService, IScopedService1 +{ + protected override string ServiceName => nameof(ScopedService1); +} + +public class ScopedService2 : DisposedService, IScopedService2 +{ + protected override string ServiceName => nameof(ScopedService2); +} + +// Реализации Transient +public class TransientService1 : DisposedService, ITransientService1 +{ + protected override string ServiceName => nameof(TransientService1); +} + +public class TransientService2 : DisposedService, ITransientService2 +{ + protected override string ServiceName => nameof(TransientService2); +} \ No newline at end of file diff --git a/TaskHub/Api/DependencyInjection/ServiceProviderExtensions.cs b/TaskHub/Api/DependencyInjection/ServiceProviderExtensions.cs new file mode 100644 index 0000000..addba1c --- /dev/null +++ b/TaskHub/Api/DependencyInjection/ServiceProviderExtensions.cs @@ -0,0 +1,23 @@ +namespace Api.DependencyInjection; + +public static class ServiceProviderExtensions +{ + public static void DemonstrateServiceLifetime(this IServiceProvider serviceProvider, string serviceName) + where TService : class, IHasInstanceId + { + Console.WriteLine($"\nДемонстрация {serviceName}"); + + var first = serviceProvider.GetService(); + var second = serviceProvider.GetService(); + + if (first == null || second == null) + { + Console.WriteLine($"Не удалось получить сервис {serviceName}"); + return; + } + + Console.WriteLine($"Первый InstanceId: {first.InstanceId}"); + Console.WriteLine($"Второй InstanceId: {second.InstanceId}"); + Console.WriteLine($"Это один и тот же объект: {ReferenceEquals(first, second)}"); + } +} \ No newline at end of file diff --git a/TaskHub/Api/Middleware/ResponseTimeMiddleware.cs b/TaskHub/Api/Middleware/ResponseTimeMiddleware.cs new file mode 100644 index 0000000..24680cf --- /dev/null +++ b/TaskHub/Api/Middleware/ResponseTimeMiddleware.cs @@ -0,0 +1,38 @@ +using System.Diagnostics; + +namespace Api.Middleware; + +/// +/// Middleware для измерения времени обработки HTTP запросов. +/// Добавляет заголовок X-Response-Time-Ms с временем выполнения запроса в миллисекундах. +/// +public class ResponseTimeMiddleware +{ + private readonly RequestDelegate _next; + + public ResponseTimeMiddleware(RequestDelegate next) + { + _next = next; + } + + /// + /// Обрабатывает HTTP запрос, измеряя время его выполнения. + /// + /// Контекст HTTP запроса + public async Task InvokeAsync(HttpContext context) + { + // Запускаем измерение времени + var stopwatch = Stopwatch.StartNew(); + + // Регистрируем callback, который добавит заголовок с временем ответа + context.Response.OnStarting(() => + { + stopwatch.Stop(); + context.Response.Headers["X-Response-Time-Ms"] = stopwatch.ElapsedMilliseconds.ToString(); + return Task.CompletedTask; + }); + + // Передаем управление следующему middleware в конвейере + await _next(context); + } +} \ No newline at end of file diff --git a/TaskHub/Api/Middleware/StudentInfoMiddleware.cs b/TaskHub/Api/Middleware/StudentInfoMiddleware.cs new file mode 100644 index 0000000..0b3d033 --- /dev/null +++ b/TaskHub/Api/Middleware/StudentInfoMiddleware.cs @@ -0,0 +1,33 @@ +namespace Api.Middleware; + +/// +/// Middleware для добавления информации о студенте в заголовки ответа +/// +public class StudentInfoMiddleware +{ + private readonly RequestDelegate _next; + + /// + /// Конструктор middleware + /// + /// Следующий middleware в конвейере + public StudentInfoMiddleware(RequestDelegate next) + { + _next = next; + } + + /// + /// Обработка HTTP-запроса + /// + /// HTTP контекст + public async Task InvokeAsync(HttpContext context) + { + context.Response.OnStarting(() => + { + context.Response.Headers["X-Student-Group"] = "RI-240947"; + context.Response.Headers["X-Student-Name"] = "Khaliullin Almaz Ildarovich"; + return Task.CompletedTask; + }); + await _next(context); + } +} \ No newline at end of file diff --git a/TaskHub/Api/ModelBinders/FromRouteTaskIdAttribute.cs b/TaskHub/Api/ModelBinders/FromRouteTaskIdAttribute.cs new file mode 100644 index 0000000..619f718 --- /dev/null +++ b/TaskHub/Api/ModelBinders/FromRouteTaskIdAttribute.cs @@ -0,0 +1,13 @@ +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; + +namespace Api.ModelBinders; + +[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = true)] +public sealed class FromRouteTaskIdAttribute : ModelBinderAttribute +{ + public FromRouteTaskIdAttribute() : base(typeof(TaskIdModelBinder)) + { + BindingSource = BindingSource.Path; + } +} diff --git a/TaskHub/Api/ModelBinders/TaskIdModelBinder.cs b/TaskHub/Api/ModelBinders/TaskIdModelBinder.cs new file mode 100644 index 0000000..2578193 --- /dev/null +++ b/TaskHub/Api/ModelBinders/TaskIdModelBinder.cs @@ -0,0 +1,39 @@ +using Microsoft.AspNetCore.Mvc.ModelBinding; + +namespace Api.ModelBinders; + + +internal sealed class TaskIdModelBinder : IModelBinder +{ + public Task BindModelAsync(ModelBindingContext bindingContext) + { + ArgumentNullException.ThrowIfNull(bindingContext); + + var modelName = bindingContext.ModelName; + var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName); + + if (valueProviderResult == ValueProviderResult.None + || string.IsNullOrWhiteSpace(valueProviderResult.FirstValue)) + { + bindingContext.ActionContext.ModelState.AddModelError( + modelName, + "Идентификатор задачи не задан"); + bindingContext.Result = ModelBindingResult.Failed(); + return Task.CompletedTask; + } + + var rawValue = valueProviderResult.FirstValue; + + if (!Guid.TryParse(rawValue, out var taskId)) + { + bindingContext.ActionContext.ModelState.AddModelError( + modelName, + "Идентификатор задачи имеет некорректный формат"); + bindingContext.Result = ModelBindingResult.Failed(); + return Task.CompletedTask; + } + + bindingContext.Result = ModelBindingResult.Success(taskId); + return Task.CompletedTask; + } +} diff --git a/TaskHub/Api/Program.cs b/TaskHub/Api/Program.cs index 6c9086d..05c6ace 100644 --- a/TaskHub/Api/Program.cs +++ b/TaskHub/Api/Program.cs @@ -1,24 +1,63 @@ +using Api.DependencyInjection; using LoggingLibrary; namespace Api; -/// -/// Точка входа приложения -/// public sealed class Program { - /// - /// Запуск приложения - /// public static void Main(string[] args) { - Host.CreateDefaultBuilder(args) + Console.WriteLine("Жизненные циклы DI"); + + var host = Host.CreateDefaultBuilder(args) .UseInfraSerilog() .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup(); }) - .Build() - .Run(); + .Build(); + + var serviceProvider = host.Services; + + + Console.WriteLine("\nСоздание Singleton сервисов"); + using (var tempScope = serviceProvider.CreateScope()) + { + // Резолвим Singleton для создания + tempScope.ServiceProvider.GetService(); + tempScope.ServiceProvider.GetService(); + } + + + Console.WriteLine("\nПервый scope"); + using (var scope1 = serviceProvider.CreateScope()) + { + DemonstrateAllServices(scope1.ServiceProvider, "первом scope"); + } + + Console.WriteLine("\nВторой scope"); + using (var scope2 = serviceProvider.CreateScope()) + { + DemonstrateAllServices(scope2.ServiceProvider, "втором scope"); + } + + host.Run(); + } + + private static void DemonstrateAllServices(IServiceProvider serviceProvider, string scopeName) + { + Console.WriteLine($"\nДемонстрация в {scopeName}:"); + + + serviceProvider.DemonstrateServiceLifetime("SingletonService1"); + serviceProvider.DemonstrateServiceLifetime("SingletonService2"); + + + serviceProvider.DemonstrateServiceLifetime("ScopedService1"); + serviceProvider.DemonstrateServiceLifetime("ScopedService2"); + + + serviceProvider.DemonstrateServiceLifetime("TransientService1"); + serviceProvider.DemonstrateServiceLifetime("TransientService2"); } } \ No newline at end of file diff --git a/TaskHub/Api/StartUp.cs b/TaskHub/Api/StartUp.cs index 9220ca4..a940ce0 100644 --- a/TaskHub/Api/StartUp.cs +++ b/TaskHub/Api/StartUp.cs @@ -1,3 +1,5 @@ +using Api.DependencyInjection; +using Api.Middleware; using Api.UseCases.Users; using Api.UseCases.Users.Interfaces; using Dal; @@ -61,6 +63,15 @@ public void ConfigureServices(IServiceCollection services) Version = "v1" }); }); + + services.AddSingleton(); + services.AddSingleton(); + + services.AddScoped(); + services.AddScoped(); + + services.AddTransient(); + services.AddTransient(); } /// @@ -81,6 +92,9 @@ public void Configure(IApplicationBuilder app) app.UseRouting(); + app.UseMiddleware(); + app.UseMiddleware(); + app.UseEndpoints(endpoints => { endpoints.MapControllers(); diff --git a/TaskHub/Dal/Context/TaskDbContext.cs b/TaskHub/Dal/Context/TaskDbContext.cs new file mode 100644 index 0000000..22f0994 --- /dev/null +++ b/TaskHub/Dal/Context/TaskDbContext.cs @@ -0,0 +1,70 @@ +using Dal.Entities; +using Microsoft.EntityFrameworkCore; + +namespace Dal.Context; + +/// +/// Контекст базы данных задач +/// +public sealed class TaskDbContext : DbContext +{ + public TaskDbContext(DbContextOptions options) + : base(options) + { + } + + /// + /// Задачи + /// + public DbSet Tasks => Set(); + + /// + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + // Таблица users управляется UserDbContext, здесь она нужна только для настройки внешнего ключа + modelBuilder.Entity(entity => + { + entity.ToTable("users", t => t.ExcludeFromMigrations()); + + entity.HasKey(x => x.Id); + + entity.Property(x => x.Name) + .HasColumnName("name") + .HasMaxLength(200); + + entity.Property(x => x.LastActivityUtc) + .HasColumnName("last_activity_utc") + .IsRequired(); + }); + + modelBuilder.Entity(entity => + { + entity.ToTable("tasks"); + + entity.HasKey(x => x.Id); + + entity.Property(x => x.Title) + .HasColumnName("title") + .HasMaxLength(500); + + entity.Property(x => x.CreatedByUserId) + .HasColumnName("created_by_user_id") + .IsRequired(); + + entity.Property(x => x.CreatedUtc) + .HasColumnName("created_utc") + .IsRequired(); + + // Связь один ко многим: один пользователь — много задач. + // Внешний ключ created_by_user_id ссылается на таблицу users. + entity.HasOne(x => x.CreatedByUser) + .WithMany() + .HasForeignKey(x => x.CreatedByUserId) + .OnDelete(DeleteBehavior.Cascade); + + entity.HasIndex(x => x.CreatedByUserId); + }); + + base.OnModelCreating(modelBuilder); + } +} diff --git a/TaskHub/Dal/DalStartUp.cs b/TaskHub/Dal/DalStartUp.cs index f6dfa82..b5a6be4 100644 --- a/TaskHub/Dal/DalStartUp.cs +++ b/TaskHub/Dal/DalStartUp.cs @@ -18,6 +18,9 @@ public static class DalStartUp public static void AddDal(this IServiceCollection services) { services.AddDatabase(); + services.AddDatabase(); + services.AddScoped(); + services.AddScoped(); } } diff --git a/TaskHub/Dal/Entities/TaskEntity.cs b/TaskHub/Dal/Entities/TaskEntity.cs new file mode 100644 index 0000000..707eff1 --- /dev/null +++ b/TaskHub/Dal/Entities/TaskEntity.cs @@ -0,0 +1,32 @@ +namespace Dal.Entities; + +/// +/// Задача +/// +public sealed class TaskEntity +{ + /// + /// Идентификатор задачи + /// + public Guid Id { get; set; } + + /// + /// Название задачи + /// + public string? Title { get; set; } + + /// + /// Идентификатор пользователя, создавшего задачу + /// + public Guid CreatedByUserId { get; set; } + + /// + /// Дата и время создания задачи в UTC + /// + public DateTimeOffset CreatedUtc { get; set; } + + /// + /// Пользователь, создавший задачу (навигационное свойство) + /// + public User? CreatedByUser { get; set; } +} diff --git a/TaskHub/Dal/Migrations/20260311124204_CreateUsers.Designer.cs b/TaskHub/Dal/Migrations/20260311124204_CreateUsers.Designer.cs new file mode 100644 index 0000000..63f758b --- /dev/null +++ b/TaskHub/Dal/Migrations/20260311124204_CreateUsers.Designer.cs @@ -0,0 +1,50 @@ +// +using System; +using Dal.Context; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Dal.Migrations +{ + [DbContext(typeof(UserDbContext))] + [Migration("20260311124204_CreateUsers")] + partial class CreateUsers + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Dal.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("LastActivityUtc") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_activity_utc"); + + b.Property("Name") + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("name"); + + b.HasKey("Id"); + + b.ToTable("users", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/TaskHub/Dal/Migrations/20260311124204_CreateUsers.cs b/TaskHub/Dal/Migrations/20260311124204_CreateUsers.cs new file mode 100644 index 0000000..10c712a --- /dev/null +++ b/TaskHub/Dal/Migrations/20260311124204_CreateUsers.cs @@ -0,0 +1,35 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Dal.Migrations +{ + /// + public partial class CreateUsers : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "users", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + name = table.Column(type: "character varying(200)", maxLength: 200, nullable: true), + last_activity_utc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_users", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "users"); + } + } +} diff --git a/TaskHub/Dal/Migrations/TaskMigrations/20260530180000_CreateTasks.Designer.cs b/TaskHub/Dal/Migrations/TaskMigrations/20260530180000_CreateTasks.Designer.cs new file mode 100644 index 0000000..4867d4a --- /dev/null +++ b/TaskHub/Dal/Migrations/TaskMigrations/20260530180000_CreateTasks.Designer.cs @@ -0,0 +1,90 @@ +// +using System; +using Dal.Context; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Dal.Migrations.TaskMigrations +{ + [DbContext(typeof(TaskDbContext))] + [Migration("20260530180000_CreateTasks")] + partial class CreateTasks + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Dal.Entities.TaskEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid") + .HasColumnName("created_by_user_id"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_utc"); + + b.Property("Title") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("title"); + + b.HasKey("Id"); + + b.HasIndex("CreatedByUserId"); + + b.ToTable("tasks", (string)null); + }); + + modelBuilder.Entity("Dal.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("LastActivityUtc") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_activity_utc"); + + b.Property("Name") + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("name"); + + b.HasKey("Id"); + + b.ToTable("users", (string)null, t => + { + t.ExcludeFromMigrations(); + }); + }); + + modelBuilder.Entity("Dal.Entities.TaskEntity", b => + { + b.HasOne("Dal.Entities.User", "CreatedByUser") + .WithMany() + .HasForeignKey("CreatedByUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CreatedByUser"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/TaskHub/Dal/Migrations/TaskMigrations/20260530180000_CreateTasks.cs b/TaskHub/Dal/Migrations/TaskMigrations/20260530180000_CreateTasks.cs new file mode 100644 index 0000000..89c80cf --- /dev/null +++ b/TaskHub/Dal/Migrations/TaskMigrations/20260530180000_CreateTasks.cs @@ -0,0 +1,47 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Dal.Migrations.TaskMigrations +{ + /// + public partial class CreateTasks : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "tasks", + columns: table => new + { + Id = table.Column(type: "uuid", nullable: false), + title = table.Column(type: "character varying(500)", maxLength: 500, nullable: true), + created_by_user_id = table.Column(type: "uuid", nullable: false), + created_utc = table.Column(type: "timestamp with time zone", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_tasks", x => x.Id); + table.ForeignKey( + name: "FK_tasks_users_created_by_user_id", + column: x => x.created_by_user_id, + principalTable: "users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_tasks_created_by_user_id", + table: "tasks", + column: "created_by_user_id"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "tasks"); + } + } +} diff --git a/TaskHub/Dal/Migrations/TaskMigrations/TaskDbContextModelSnapshot.cs b/TaskHub/Dal/Migrations/TaskMigrations/TaskDbContextModelSnapshot.cs new file mode 100644 index 0000000..c67dbaf --- /dev/null +++ b/TaskHub/Dal/Migrations/TaskMigrations/TaskDbContextModelSnapshot.cs @@ -0,0 +1,87 @@ +// +using System; +using Dal.Context; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Dal.Migrations.TaskMigrations +{ + [DbContext(typeof(TaskDbContext))] + partial class TaskDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Dal.Entities.TaskEntity", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("CreatedByUserId") + .HasColumnType("uuid") + .HasColumnName("created_by_user_id"); + + b.Property("CreatedUtc") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_utc"); + + b.Property("Title") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("title"); + + b.HasKey("Id"); + + b.HasIndex("CreatedByUserId"); + + b.ToTable("tasks", (string)null); + }); + + modelBuilder.Entity("Dal.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("LastActivityUtc") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_activity_utc"); + + b.Property("Name") + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("name"); + + b.HasKey("Id"); + + b.ToTable("users", (string)null, t => + { + t.ExcludeFromMigrations(); + }); + }); + + modelBuilder.Entity("Dal.Entities.TaskEntity", b => + { + b.HasOne("Dal.Entities.User", "CreatedByUser") + .WithMany() + .HasForeignKey("CreatedByUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("CreatedByUser"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/TaskHub/Dal/Migrations/UserDbContextModelSnapshot.cs b/TaskHub/Dal/Migrations/UserDbContextModelSnapshot.cs new file mode 100644 index 0000000..19485c0 --- /dev/null +++ b/TaskHub/Dal/Migrations/UserDbContextModelSnapshot.cs @@ -0,0 +1,47 @@ +// +using System; +using Dal.Context; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace Dal.Migrations +{ + [DbContext(typeof(UserDbContext))] + partial class UserDbContextModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.2") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Dal.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid"); + + b.Property("LastActivityUtc") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_activity_utc"); + + b.Property("Name") + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("name"); + + b.HasKey("Id"); + + b.ToTable("users", (string)null); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/TaskHub/Dal/Repositories/Interfaces/ITaskRepository.cs b/TaskHub/Dal/Repositories/Interfaces/ITaskRepository.cs new file mode 100644 index 0000000..c2531b7 --- /dev/null +++ b/TaskHub/Dal/Repositories/Interfaces/ITaskRepository.cs @@ -0,0 +1,60 @@ +using Dal.Entities; + +namespace Dal.Repositories.Interfaces; + +/// +/// Репозиторий задач +/// +public interface ITaskRepository +{ + /// + /// Создать задачу + /// + /// Название задачи + /// Идентификатор пользователя, создавшего задачу + /// Дата и время создания задачи в UTC + /// Токен отмены + /// Созданная задача + Task CreateTaskAsync( + string? title, + Guid createdByUserId, + DateTimeOffset createdUtc, + CancellationToken cancellationToken); + + /// + /// Получить все задачи + /// + /// Токен отмены + /// Список задач + Task> GetAllTasksAsync(CancellationToken cancellationToken); + + /// + /// Получить задачу по идентификатору + /// + /// Идентификатор задачи + /// Токен отмены + /// Задача или null, если задача не найдена + Task GetTaskByIdAsync(Guid taskId, CancellationToken cancellationToken); + + /// + /// Обновить название задачи + /// + /// Идентификатор задачи + /// Новое название задачи + /// Токен отмены + Task SetTaskTitleAsync(Guid taskId, string? title, CancellationToken cancellationToken); + + /// + /// Удалить задачу по идентификатору + /// + /// Идентификатор задачи + /// Токен отмены + /// true, если задача удалена, иначе false + Task DeleteTaskByIdAsync(Guid taskId, CancellationToken cancellationToken); + + /// + /// Удалить все задачи + /// + /// Токен отмены + Task DeleteAllTasksAsync(CancellationToken cancellationToken); +} diff --git a/TaskHub/Dal/Repositories/TaskRepository.cs b/TaskHub/Dal/Repositories/TaskRepository.cs new file mode 100644 index 0000000..a63133c --- /dev/null +++ b/TaskHub/Dal/Repositories/TaskRepository.cs @@ -0,0 +1,100 @@ +using Dal.Context; +using Dal.Entities; +using Dal.Repositories.Interfaces; +using Microsoft.EntityFrameworkCore; + +namespace Dal.Repositories; + +/// +public sealed class TaskRepository : ITaskRepository +{ + /// + /// Контекст базы данных задач + /// + private readonly TaskDbContext _dbContext; + + public TaskRepository(TaskDbContext dbContext) + { + _dbContext = dbContext; + } + + /// + public async Task CreateTaskAsync( + string? title, + Guid createdByUserId, + DateTimeOffset createdUtc, + CancellationToken cancellationToken) + { + var task = new TaskEntity + { + Id = Guid.NewGuid(), + Title = title, + CreatedByUserId = createdByUserId, + CreatedUtc = createdUtc + }; + + _dbContext.Tasks.Add(task); + await _dbContext.SaveChangesAsync(cancellationToken); + + return task; + } + + /// + public async Task> GetAllTasksAsync(CancellationToken cancellationToken) + { + var tasks = await _dbContext.Tasks + .AsNoTracking() + .ToListAsync(cancellationToken); + + return tasks.AsReadOnly(); + } + + /// + public async Task GetTaskByIdAsync(Guid taskId, CancellationToken cancellationToken) + { + return await _dbContext.Tasks + .AsNoTracking() + .FirstOrDefaultAsync(x => x.Id == taskId, cancellationToken); + } + + /// + public async Task SetTaskTitleAsync(Guid taskId, string? title, CancellationToken cancellationToken) + { + var task = await _dbContext.Tasks.FirstOrDefaultAsync(x => x.Id == taskId, cancellationToken); + if (task is null) + { + return; + } + + task.Title = title; + await _dbContext.SaveChangesAsync(cancellationToken); + } + + /// + public async Task DeleteTaskByIdAsync(Guid taskId, CancellationToken cancellationToken) + { + var task = await _dbContext.Tasks.FirstOrDefaultAsync(x => x.Id == taskId, cancellationToken); + if (task is null) + { + return false; + } + + _dbContext.Tasks.Remove(task); + await _dbContext.SaveChangesAsync(cancellationToken); + + return true; + } + + /// + public async Task DeleteAllTasksAsync(CancellationToken cancellationToken) + { + var tasks = await _dbContext.Tasks.ToListAsync(cancellationToken); + if (tasks.Count is 0) + { + return; + } + + _dbContext.Tasks.RemoveRange(tasks); + await _dbContext.SaveChangesAsync(cancellationToken); + } +} diff --git a/TaskHub/Logic/LogicStartUp.cs b/TaskHub/Logic/LogicStartUp.cs index 6fc3e70..ccae6a1 100644 --- a/TaskHub/Logic/LogicStartUp.cs +++ b/TaskHub/Logic/LogicStartUp.cs @@ -1,4 +1,8 @@ -using Logic.Users.Services; +using Logic.Tasks.Services; +using Logic.Tasks.Services.Interfaces; +using Logic.Tasks.UseCases; +using Logic.Tasks.UseCases.Interfaces; +using Logic.Users.Services; using Logic.Users.Services.Interfaces; using Microsoft.Extensions.DependencyInjection; @@ -16,5 +20,14 @@ public static class LogicStartUp public static void AddLogic(this IServiceCollection services) { services.AddScoped(); + + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + services.AddScoped(); + + services.AddScoped(); } -} \ No newline at end of file +} diff --git a/TaskHub/Logic/Tasks/Models/TaskModel.cs b/TaskHub/Logic/Tasks/Models/TaskModel.cs new file mode 100644 index 0000000..7a7b79f --- /dev/null +++ b/TaskHub/Logic/Tasks/Models/TaskModel.cs @@ -0,0 +1,38 @@ +namespace Logic.Tasks.Models; + +/// +/// Модель задачи для слоя логики +/// +public sealed class TaskModel +{ + /// + /// Идентификатор задачи + /// + public Guid Id { get; } + + /// + /// Название задачи + /// + public string? Title { get; } + + /// + /// Идентификатор пользователя, создавшего задачу + /// + public Guid CreatedByUserId { get; } + + /// + /// Дата и время создания задачи в UTC + /// + public DateTimeOffset CreatedUtc { get; } + + /// + /// Конструктор + /// + public TaskModel(Guid id, string? title, Guid createdByUserId, DateTimeOffset createdUtc) + { + Id = id; + Title = title; + CreatedByUserId = createdByUserId; + CreatedUtc = createdUtc; + } +} diff --git a/TaskHub/Logic/Tasks/Services/Interfaces/ITaskService.cs b/TaskHub/Logic/Tasks/Services/Interfaces/ITaskService.cs new file mode 100644 index 0000000..a6fb60f --- /dev/null +++ b/TaskHub/Logic/Tasks/Services/Interfaces/ITaskService.cs @@ -0,0 +1,55 @@ +using Logic.Tasks.Models; + +namespace Logic.Tasks.Services.Interfaces; + +/// +/// Сервис задач +/// +public interface ITaskService +{ + /// + /// Создать задачу + /// + /// Название задачи + /// Идентификатор пользователя, создавшего задачу + /// Токен отмены + /// Модель задачи + Task CreateTaskAsync(string? title, Guid createdByUserId, CancellationToken cancellationToken); + + /// + /// Получить все задачи + /// + /// Токен отмены + /// Список задач + Task> GetAllTasksAsync(CancellationToken cancellationToken); + + /// + /// Получить задачу по идентификатору + /// + /// Идентификатор задачи + /// Токен отмены + /// Модель задачи или null, если задача не найдена + Task GetTaskByIdAsync(Guid taskId, CancellationToken cancellationToken); + + /// + /// Изменить название задачи + /// + /// Идентификатор задачи + /// Название задачи + /// Токен отмены + Task SetTaskTitleAsync(Guid taskId, string? title, CancellationToken cancellationToken); + + /// + /// Удалить задачу по идентификатору + /// + /// Идентификатор задачи + /// Токен отмены + /// true, если задача удалена, иначе false + Task DeleteTaskByIdAsync(Guid taskId, CancellationToken cancellationToken); + + /// + /// Удалить все задачи + /// + /// Токен отмены + Task DeleteAllTasksAsync(CancellationToken cancellationToken); +} diff --git a/TaskHub/Logic/Tasks/Services/TaskService.cs b/TaskHub/Logic/Tasks/Services/TaskService.cs new file mode 100644 index 0000000..e52e9e1 --- /dev/null +++ b/TaskHub/Logic/Tasks/Services/TaskService.cs @@ -0,0 +1,91 @@ +using Logic.Tasks.Models; +using Logic.Tasks.Services.Interfaces; +using Logic.Tasks.UseCases.Interfaces; + +namespace Logic.Tasks.Services; + +/// +internal sealed class TaskService : ITaskService +{ + /// + /// UseCase создания задачи + /// + private readonly ICreateTaskUseCase _createTaskUseCase; + + /// + /// UseCase получения всех задач + /// + private readonly IGetTasksUseCase _getTasksUseCase; + + /// + /// UseCase получения задачи по идентификатору + /// + private readonly IGetTaskUseCase _getTaskUseCase; + + /// + /// UseCase изменения названия задачи + /// + private readonly ISetTaskTitleUseCase _setTaskTitleUseCase; + + /// + /// UseCase удаления задачи + /// + private readonly IDeleteTaskUseCase _deleteTaskUseCase; + + /// + /// UseCase удаления всех задач + /// + private readonly IDeleteTasksUseCase _deleteTasksUseCase; + + public TaskService( + ICreateTaskUseCase createTaskUseCase, + IGetTasksUseCase getTasksUseCase, + IGetTaskUseCase getTaskUseCase, + ISetTaskTitleUseCase setTaskTitleUseCase, + IDeleteTaskUseCase deleteTaskUseCase, + IDeleteTasksUseCase deleteTasksUseCase) + { + _createTaskUseCase = createTaskUseCase; + _getTasksUseCase = getTasksUseCase; + _getTaskUseCase = getTaskUseCase; + _setTaskTitleUseCase = setTaskTitleUseCase; + _deleteTaskUseCase = deleteTaskUseCase; + _deleteTasksUseCase = deleteTasksUseCase; + } + + /// + public Task CreateTaskAsync(string? title, Guid createdByUserId, CancellationToken cancellationToken) + { + return _createTaskUseCase.ExecuteAsync(title, createdByUserId, cancellationToken); + } + + /// + public Task> GetAllTasksAsync(CancellationToken cancellationToken) + { + return _getTasksUseCase.ExecuteAsync(cancellationToken); + } + + /// + public Task GetTaskByIdAsync(Guid taskId, CancellationToken cancellationToken) + { + return _getTaskUseCase.ExecuteAsync(taskId, cancellationToken); + } + + /// + public Task SetTaskTitleAsync(Guid taskId, string? title, CancellationToken cancellationToken) + { + return _setTaskTitleUseCase.ExecuteAsync(taskId, title, cancellationToken); + } + + /// + public Task DeleteTaskByIdAsync(Guid taskId, CancellationToken cancellationToken) + { + return _deleteTaskUseCase.ExecuteAsync(taskId, cancellationToken); + } + + /// + public Task DeleteAllTasksAsync(CancellationToken cancellationToken) + { + return _deleteTasksUseCase.ExecuteAsync(cancellationToken); + } +} diff --git a/TaskHub/Logic/Tasks/UseCases/CreateTaskUseCase.cs b/TaskHub/Logic/Tasks/UseCases/CreateTaskUseCase.cs new file mode 100644 index 0000000..d2fe42f --- /dev/null +++ b/TaskHub/Logic/Tasks/UseCases/CreateTaskUseCase.cs @@ -0,0 +1,26 @@ +using Dal.Repositories.Interfaces; +using Logic.Tasks.Models; +using Logic.Tasks.UseCases.Interfaces; + +namespace Logic.Tasks.UseCases; + +/// +internal sealed class CreateTaskUseCase : ICreateTaskUseCase +{ + /// + /// Репозиторий задач + /// + private readonly ITaskRepository _taskRepository; + + public CreateTaskUseCase(ITaskRepository taskRepository) + { + _taskRepository = taskRepository; + } + + /// + public async Task ExecuteAsync(string? title, Guid createdByUserId, CancellationToken cancellationToken) + { + var task = await _taskRepository.CreateTaskAsync(title, createdByUserId, DateTimeOffset.UtcNow, cancellationToken); + return new TaskModel(task.Id, task.Title, task.CreatedByUserId, task.CreatedUtc); + } +} diff --git a/TaskHub/Logic/Tasks/UseCases/DeleteTaskUseCase.cs b/TaskHub/Logic/Tasks/UseCases/DeleteTaskUseCase.cs new file mode 100644 index 0000000..c9f16eb --- /dev/null +++ b/TaskHub/Logic/Tasks/UseCases/DeleteTaskUseCase.cs @@ -0,0 +1,24 @@ +using Dal.Repositories.Interfaces; +using Logic.Tasks.UseCases.Interfaces; + +namespace Logic.Tasks.UseCases; + +/// +internal sealed class DeleteTaskUseCase : IDeleteTaskUseCase +{ + /// + /// Репозиторий задач + /// + private readonly ITaskRepository _taskRepository; + + public DeleteTaskUseCase(ITaskRepository taskRepository) + { + _taskRepository = taskRepository; + } + + /// + public async Task ExecuteAsync(Guid taskId, CancellationToken cancellationToken) + { + return await _taskRepository.DeleteTaskByIdAsync(taskId, cancellationToken); + } +} diff --git a/TaskHub/Logic/Tasks/UseCases/DeleteTasksUseCase.cs b/TaskHub/Logic/Tasks/UseCases/DeleteTasksUseCase.cs new file mode 100644 index 0000000..68819f3 --- /dev/null +++ b/TaskHub/Logic/Tasks/UseCases/DeleteTasksUseCase.cs @@ -0,0 +1,24 @@ +using Dal.Repositories.Interfaces; +using Logic.Tasks.UseCases.Interfaces; + +namespace Logic.Tasks.UseCases; + +/// +internal sealed class DeleteTasksUseCase : IDeleteTasksUseCase +{ + /// + /// Репозиторий задач + /// + private readonly ITaskRepository _taskRepository; + + public DeleteTasksUseCase(ITaskRepository taskRepository) + { + _taskRepository = taskRepository; + } + + /// + public async Task ExecuteAsync(CancellationToken cancellationToken) + { + await _taskRepository.DeleteAllTasksAsync(cancellationToken); + } +} diff --git a/TaskHub/Logic/Tasks/UseCases/GetTaskUseCase.cs b/TaskHub/Logic/Tasks/UseCases/GetTaskUseCase.cs new file mode 100644 index 0000000..652aaae --- /dev/null +++ b/TaskHub/Logic/Tasks/UseCases/GetTaskUseCase.cs @@ -0,0 +1,32 @@ +using Dal.Repositories.Interfaces; +using Logic.Tasks.Models; +using Logic.Tasks.UseCases.Interfaces; + +namespace Logic.Tasks.UseCases; + +/// +internal sealed class GetTaskUseCase : IGetTaskUseCase +{ + /// + /// Репозиторий задач + /// + private readonly ITaskRepository _taskRepository; + + public GetTaskUseCase(ITaskRepository taskRepository) + { + _taskRepository = taskRepository; + } + + /// + public async Task ExecuteAsync(Guid taskId, CancellationToken cancellationToken) + { + var task = await _taskRepository.GetTaskByIdAsync(taskId, cancellationToken); + + if (task is null) + { + return null; + } + + return new TaskModel(task.Id, task.Title, task.CreatedByUserId, task.CreatedUtc); + } +} diff --git a/TaskHub/Logic/Tasks/UseCases/GetTasksUseCase.cs b/TaskHub/Logic/Tasks/UseCases/GetTasksUseCase.cs new file mode 100644 index 0000000..494c786 --- /dev/null +++ b/TaskHub/Logic/Tasks/UseCases/GetTasksUseCase.cs @@ -0,0 +1,30 @@ +using Dal.Repositories.Interfaces; +using Logic.Tasks.Models; +using Logic.Tasks.UseCases.Interfaces; + +namespace Logic.Tasks.UseCases; + +/// +internal sealed class GetTasksUseCase : IGetTasksUseCase +{ + /// + /// Репозиторий задач + /// + private readonly ITaskRepository _taskRepository; + + public GetTasksUseCase(ITaskRepository taskRepository) + { + _taskRepository = taskRepository; + } + + /// + public async Task> ExecuteAsync(CancellationToken cancellationToken) + { + var tasks = await _taskRepository.GetAllTasksAsync(cancellationToken); + + return tasks + .Select(x => new TaskModel(x.Id, x.Title, x.CreatedByUserId, x.CreatedUtc)) + .ToList() + .AsReadOnly(); + } +} diff --git a/TaskHub/Logic/Tasks/UseCases/Interfaces/ICreateTaskUseCase.cs b/TaskHub/Logic/Tasks/UseCases/Interfaces/ICreateTaskUseCase.cs new file mode 100644 index 0000000..53ebfc5 --- /dev/null +++ b/TaskHub/Logic/Tasks/UseCases/Interfaces/ICreateTaskUseCase.cs @@ -0,0 +1,18 @@ +using Logic.Tasks.Models; + +namespace Logic.Tasks.UseCases.Interfaces; + +/// +/// UseCase создания задачи +/// +public interface ICreateTaskUseCase +{ + /// + /// Выполнить создание задачи + /// + /// Название задачи + /// Идентификатор пользователя, создавшего задачу + /// Токен отмены + /// Созданная задача + Task ExecuteAsync(string? title, Guid createdByUserId, CancellationToken cancellationToken); +} diff --git a/TaskHub/Logic/Tasks/UseCases/Interfaces/IDeleteTaskUseCase.cs b/TaskHub/Logic/Tasks/UseCases/Interfaces/IDeleteTaskUseCase.cs new file mode 100644 index 0000000..e282dce --- /dev/null +++ b/TaskHub/Logic/Tasks/UseCases/Interfaces/IDeleteTaskUseCase.cs @@ -0,0 +1,15 @@ +namespace Logic.Tasks.UseCases.Interfaces; + +/// +/// UseCase удаления задачи по идентификатору +/// +public interface IDeleteTaskUseCase +{ + /// + /// Выполнить удаление задачи по идентификатору + /// + /// Идентификатор задачи + /// Токен отмены + /// true, если задача удалена, иначе false + Task ExecuteAsync(Guid taskId, CancellationToken cancellationToken); +} diff --git a/TaskHub/Logic/Tasks/UseCases/Interfaces/IDeleteTasksUseCase.cs b/TaskHub/Logic/Tasks/UseCases/Interfaces/IDeleteTasksUseCase.cs new file mode 100644 index 0000000..a740a00 --- /dev/null +++ b/TaskHub/Logic/Tasks/UseCases/Interfaces/IDeleteTasksUseCase.cs @@ -0,0 +1,13 @@ +namespace Logic.Tasks.UseCases.Interfaces; + +/// +/// UseCase удаления всех задач +/// +public interface IDeleteTasksUseCase +{ + /// + /// Выполнить удаление всех задач + /// + /// Токен отмены + Task ExecuteAsync(CancellationToken cancellationToken); +} diff --git a/TaskHub/Logic/Tasks/UseCases/Interfaces/IGetTaskUseCase.cs b/TaskHub/Logic/Tasks/UseCases/Interfaces/IGetTaskUseCase.cs new file mode 100644 index 0000000..cbed2fb --- /dev/null +++ b/TaskHub/Logic/Tasks/UseCases/Interfaces/IGetTaskUseCase.cs @@ -0,0 +1,17 @@ +using Logic.Tasks.Models; + +namespace Logic.Tasks.UseCases.Interfaces; + +/// +/// UseCase получения задачи по идентификатору +/// +public interface IGetTaskUseCase +{ + /// + /// Выполнить получение задачи по идентификатору + /// + /// Идентификатор задачи + /// Токен отмены + /// Задача или null, если задача не найдена + Task ExecuteAsync(Guid taskId, CancellationToken cancellationToken); +} diff --git a/TaskHub/Logic/Tasks/UseCases/Interfaces/IGetTasksUseCase.cs b/TaskHub/Logic/Tasks/UseCases/Interfaces/IGetTasksUseCase.cs new file mode 100644 index 0000000..9a34621 --- /dev/null +++ b/TaskHub/Logic/Tasks/UseCases/Interfaces/IGetTasksUseCase.cs @@ -0,0 +1,16 @@ +using Logic.Tasks.Models; + +namespace Logic.Tasks.UseCases.Interfaces; + +/// +/// UseCase получения всех задач +/// +public interface IGetTasksUseCase +{ + /// + /// Выполнить получение всех задач + /// + /// Токен отмены + /// Список задач + Task> ExecuteAsync(CancellationToken cancellationToken); +} diff --git a/TaskHub/Logic/Tasks/UseCases/Interfaces/ISetTaskTitleUseCase.cs b/TaskHub/Logic/Tasks/UseCases/Interfaces/ISetTaskTitleUseCase.cs new file mode 100644 index 0000000..d5e7bc4 --- /dev/null +++ b/TaskHub/Logic/Tasks/UseCases/Interfaces/ISetTaskTitleUseCase.cs @@ -0,0 +1,15 @@ +namespace Logic.Tasks.UseCases.Interfaces; + +/// +/// UseCase изменения названия задачи +/// +public interface ISetTaskTitleUseCase +{ + /// + /// Выполнить изменение названия задачи + /// + /// Идентификатор задачи + /// Новое название задачи + /// Токен отмены + Task ExecuteAsync(Guid taskId, string? title, CancellationToken cancellationToken); +} diff --git a/TaskHub/Logic/Tasks/UseCases/SetTaskTitleUseCase.cs b/TaskHub/Logic/Tasks/UseCases/SetTaskTitleUseCase.cs new file mode 100644 index 0000000..25b1a62 --- /dev/null +++ b/TaskHub/Logic/Tasks/UseCases/SetTaskTitleUseCase.cs @@ -0,0 +1,24 @@ +using Dal.Repositories.Interfaces; +using Logic.Tasks.UseCases.Interfaces; + +namespace Logic.Tasks.UseCases; + +/// +internal sealed class SetTaskTitleUseCase : ISetTaskTitleUseCase +{ + /// + /// Репозиторий задач + /// + private readonly ITaskRepository _taskRepository; + + public SetTaskTitleUseCase(ITaskRepository taskRepository) + { + _taskRepository = taskRepository; + } + + /// + public async Task ExecuteAsync(Guid taskId, string? title, CancellationToken cancellationToken) + { + await _taskRepository.SetTaskTitleAsync(taskId, title, cancellationToken); + } +}