Replaces MVC with FastEndpoints in Lumina.Presentation.Api

This commit is contained in:
BinaryAlley committed 2024-10-23 21:34:10 +03:00
1 parent b1a20716df
commit c7b8bc2f1c
519 files changed
+15329 -8539

No files matched your search

@@ -1,64 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.AspNetCore.Mvc.ApiExplorer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
#endregion
namespace Lumina.Presentation.Api.Common.Configuration;
/// <summary>
/// Configures the Swagger options.
/// </summary>
public class ConfigureSwaggerOptions : IConfigureNamedOptions<SwaggerGenOptions>
{
private readonly IApiVersionDescriptionProvider _provider;
/// <summary>
/// Initializes a new instance of the <see cref="ConfigureSwaggerOptions"/> class.
/// </summary>
/// <param name="provider">Provider for API version descriptions.</param>
public ConfigureSwaggerOptions(IApiVersionDescriptionProvider provider)
{
_provider = provider;
}
/// <summary>
/// Configures the Swagger options.
/// </summary>
/// <param name="options">The options instance to configure.</param>
public void Configure(SwaggerGenOptions options)
{
// add swagger document for every API version discovered
foreach (ApiVersionDescription description in _provider.ApiVersionDescriptions)
options.SwaggerDoc(description.GroupName, CreateVersionInfo(description));
}
/// <summary>
/// Configures the Swagger options.
/// </summary>
/// <param name="name">The name of the options instance being configured.</param>
/// <param name="options">The options instance to configure.</param>
public void Configure(string? name, SwaggerGenOptions options)
{
Configure(options);
}
/// <summary>
/// Creates the version information for the Swagger document.
/// </summary>
/// <param name="description">The API version description.</param>
/// <returns>The created <see cref="OpenApiInfo"/> instance.</returns>
private OpenApiInfo CreateVersionInfo(ApiVersionDescription description)
{
OpenApiInfo info = new()
{
Title = "Lumina API",
Version = description.ApiVersion.ToString()
};
if (description.IsDeprecated)
info.Description += " This API version has been deprecated.";
return info;
}
}
@@ -1,11 +1,7 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Common.Converters;
using Lumina.Presentation.Api.Common.Configuration;
using Lumina.Presentation.Api.Common.Errors;
using Mapster;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using FastEndpoints;
using FastEndpoints.Swagger;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using System.Text.Json.Serialization;
#endregion
@@ -24,6 +20,40 @@ public static class PresentationApiLayerServices
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddPresentationApiLayerServices(this IServiceCollection services)
{
services.Configure<JsonOptions>(jsonOptions =>
{
jsonOptions.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
jsonOptions.SerializerOptions.MaxDepth = 256;
jsonOptions.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
});
services.AddAuthorization();
services.AddFastEndpoints(
o => o.Assemblies =
[
typeof(Program).Assembly
]);
services.SwaggerDocument(documentOptions =>
{
documentOptions.SerializerSettings = s =>
{
s.PropertyNamingPolicy = null;
s.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
};
documentOptions.MaxEndpointVersion = 1;
documentOptions.MinEndpointVersion = 1;
documentOptions.DocumentSettings = s =>
{
s.DocumentName = "Release 1.0";
s.Title = "Lumina API";
s.Version = "v1.0";
};
documentOptions.RemoveEmptyRequestSchema = true;
documentOptions.ShortSchemaNames = true;
});
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
@@ -33,41 +63,6 @@ public static class PresentationApiLayerServices
.AllowAnyHeader());
});
// add services to the container
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.MaxDepth = 256;
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles; // needed because file system API responses can have very nested structures
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
options.JsonSerializerOptions.Converters.Add(new OptionalJsonConverterFactory());
});
// add services to the container.
services.AddEndpointsApiExplorer();
services.AddSwaggerGen();
services.ConfigureOptions<ConfigureSwaggerOptions>();
services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
});
services.AddVersionedApiExplorer(options =>
{
options.GroupNameFormat = "'v'VVV";
options.SubstituteApiVersionInUrl = true;
});
services.AddSingleton<ProblemDetailsFactory, CustomProblemDetailsFactory>();
// register mapster configs
TypeAdapterConfig mapsterConfig = TypeAdapterConfig.GlobalSettings;
mapsterConfig.Scan(typeof(PresentationApiLayerServices).Assembly);
services.AddSingleton(mapsterConfig);
services.AddScoped<IMapper, ServiceMapper>();
return services;
}
}
@@ -1,118 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Presentation.Api.Common.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
#endregion
namespace Lumina.Presentation.Api.Common.Errors;
/// <summary>
/// Problem details factory which adds custom properties to the default implementation provided by Microsoft.
/// </summary>
public class CustomProblemDetailsFactory : ProblemDetailsFactory
{
private readonly ApiBehaviorOptions _options;
private readonly Action<ProblemDetailsContext>? _configure;
/// <summary>
/// Initializes a new instance of the <see cref="CustomProblemDetailsFactory"/> class.
/// </summary>
/// <param name="apiBehaviorOptions">Injected service for retrieving <see cref="ApiBehaviorOptions"/>.</param>
/// <param name="problemDetailsOptions">Injected service for retrieving <see cref="ProblemDetailsOptions"/>.</param>
/// <exception cref="ArgumentNullException">Thrown when the value of options (if any) is <see langword="null"/>.</exception>
public CustomProblemDetailsFactory(IOptions<ApiBehaviorOptions> apiBehaviorOptions, IOptions<ProblemDetailsOptions>? problemDetailsOptions = null)
{
_options = apiBehaviorOptions?.Value ?? throw new ArgumentNullException(nameof(apiBehaviorOptions));
_configure = problemDetailsOptions?.Value?.CustomizeProblemDetails;
}
/// <summary>
/// Creates a <see cref="ProblemDetails"/> instance that configures defaults based on values specified in <see cref="ApiBehaviorOptions"/>.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext"/>.</param>
/// <param name="statusCode">The value for <see cref="ProblemDetails.Status"/>.</param>
/// <param name="title">The value for <see cref="ProblemDetails.Title"/>.</param>
/// <param name="type">The value for <see cref="ProblemDetails.Type"/>.</param>
/// <param name="detail">The value for <see cref="ProblemDetails.Detail"/>.</param>
/// <param name="instance">The value for <see cref="ProblemDetails.Instance"/>.</param>
/// <returns>The <see cref="ProblemDetails"/> instance.</returns>
public override ProblemDetails CreateProblemDetails(HttpContext httpContext, int? statusCode = null, string? title = null, string? type = null,
string? detail = null, string? instance = null)
{
statusCode ??= 500;
ProblemDetails problemDetails = new()
{
Status = statusCode,
Title = title,
Type = type,
Detail = detail,
Instance = instance,
};
ApplyProblemDetailsDefaults(httpContext, problemDetails, statusCode.Value);
return problemDetails;
}
/// <summary>
/// Creates a <see cref="ValidationProblemDetails"/> instance that configures defaults based on values specified in <see cref="ApiBehaviorOptions"/>.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext" />.</param>
/// <param name="modelStateDictionary">The <see cref="ModelStateDictionary"/>.</param>
/// <param name="statusCode">The value for <see cref="ProblemDetails.Status"/>.</param>
/// <param name="title">The value for <see cref="ProblemDetails.Title"/>.</param>
/// <param name="type">The value for <see cref="ProblemDetails.Type"/>.</param>
/// <param name="detail">The value for <see cref="ProblemDetails.Detail"/>.</param>
/// <param name="instance">The value for <see cref="ProblemDetails.Instance"/>.</param>
/// <returns>The <see cref="ValidationProblemDetails"/> instance.</returns>
public override ValidationProblemDetails CreateValidationProblemDetails(HttpContext httpContext, ModelStateDictionary modelStateDictionary, int? statusCode = null,
string? title = null, string? type = null, string? detail = null, string? instance = null)
{
ArgumentNullException.ThrowIfNull(modelStateDictionary);
statusCode ??= 400;
ValidationProblemDetails problemDetails = new(modelStateDictionary)
{
Status = statusCode,
Type = type,
Detail = detail,
Instance = instance,
};
if (title != null)
problemDetails.Title = title; // for validation problem details, don't overwrite the default title with null
ApplyProblemDetailsDefaults(httpContext, problemDetails, statusCode.Value);
return problemDetails;
}
/// <summary>
/// Creates a <see cref="ValidationProblemDetails"/> instance that configures defaults based on values specified in <see cref="ApiBehaviorOptions"/>.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext" />.</param>
/// <param name="statusCode">The value for <see cref="ProblemDetails.Status"/>.</param>
/// <param name="problemDetails">The value for <see cref="ProblemDetails"/>.</param>
/// <returns>The <see cref="ValidationProblemDetails"/> instance.</returns>
private void ApplyProblemDetailsDefaults(HttpContext httpContext, ProblemDetails problemDetails, int statusCode)
{
problemDetails.Status ??= statusCode;
if (_options.ClientErrorMapping.TryGetValue(statusCode, out ClientErrorData? clientErrorData))
{
problemDetails.Title ??= clientErrorData.Title;
problemDetails.Type ??= clientErrorData.Link;
}
string? traceId = Activity.Current?.Id ?? httpContext?.TraceIdentifier;
if (traceId != null)
problemDetails.Extensions["traceId"] = traceId;
// get any errors that might be sent by ApiController base class' Problem() method
List<Error>? errors = httpContext?.Items[HttpContextItemKeys.ERRORS] as List<Error>;
// add any extra custom properties
if (errors is not null)
problemDetails.Extensions.Add("errors", errors.Select(error => error.Code));
//problemDetails.Extensions.Add("errorCodes", errors.Select(e => e.Type.ToString()));
_configure?.Invoke(new() { HttpContext = httpContext!, ProblemDetails = problemDetails });
}
}
@@ -1,27 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary;
using Mapster;
#endregion
namespace Lumina.Presentation.Api.Common.Mapping.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Mapping configuration for books between the API request object and the command object.
/// </summary>
public class BookMappingConfig : IRegister
{
/// <summary>
/// Registers the mapping configuration.
/// </summary>
/// <param name="config">The type adapter configuration.</param>
public void Register(TypeAdapterConfig config)
{
config.NewConfig<AddBookRequest, AddBookCommand>()
.Map(dest => dest.ASIN, src => src.ASIN)
.Map(dest => dest.ISBNs, src => src.ISBNs)
.Map(dest => dest.LCCN, src => src.LCCN)
.Map(dest => dest.OCLCNumber, src => src.OCLCNumber)
.MapToConstructor(true);
}
}
@@ -1,38 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Common.ModelBinders;
/// <summary>
/// Custom model binder for URL parameters. For some reason, the default binder converts "%20" to "+", instead of " ".
/// </summary>
public class UrlStringBinder : IModelBinder
{
/// <summary>
/// Binds a model to a value by using the specified controller context and binding context.
/// </summary>
/// <param name="bindingContext">The context within which to bind the model.</param>
/// <returns>A task representing the bind operation.</returns>
public Task BindModelAsync(ModelBindingContext bindingContext)
{
ArgumentNullException.ThrowIfNull(bindingContext);
string modelName = bindingContext.ModelName;
// try to fetch the value of the argument by name
ValueProviderResult valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
return Task.CompletedTask;
string? value = valueProviderResult.FirstValue;
if (value is null)
{
bindingContext.Result = ModelBindingResult.Failed();
return Task.CompletedTask;
}
// do the custom decoding here
value = Uri.UnescapeDataString(value);
bindingContext.Result = ModelBindingResult.Success(value);
return Task.CompletedTask;
}
}
@@ -0,0 +1,17 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Directories route.
/// </summary>
public static class Directories
{
public const string GET_DIRECTORY_TREE = "/directories/get-directory-tree";
public const string GET_TREE_DIRECTORIES = "/directories/get-tree-directories";
public const string GET_DIRECTORIES = "/directories/get-directories";
}
}
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Drives route.
/// </summary>
public static class Drives
{
public const string GET_DRIVES = "/drives/get-drives";
}
}
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the FileSystem route.
/// </summary>
public static class FileSystem
{
public const string GET_TYPES = "/file-system/get-type";
}
}
@@ -0,0 +1,16 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Files route.
/// </summary>
public static class Files
{
public const string GET_TREE_FILES = "/files/get-tree-files";
public const string GET_FILES = "/files/get-files";
}
}
@@ -0,0 +1,21 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Path route.
/// </summary>
public static class Path
{
public const string GET_PATH_ROOT = "/path/get-path-root";
public const string GET_PATH_SEPARATOR = "/path/get-path-separator";
public const string GET_PATH_PARENT = "/path/get-path-parent";
public const string COMBINE = "/path/combine";
public const string SPLIT = "/path/split";
public const string VALIDATE = "/path/validate";
public const string CHECK_PATH_EXISTS = "/path/check-path-exists";
}
}
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Thumbnails route.
/// </summary>
public static class Thumbnails
{
public const string GET_THUMBNAIL = "/thumbnails/get-thumbnail";
}
}
@@ -0,0 +1,15 @@
namespace Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Health route.
/// </summary>
public static class Health
{
public const string CHECK_HEALTH = "/check-health";
}
}
@@ -0,0 +1,17 @@
namespace Lumina.Presentation.Api.Common.Routes.WrittenContentLibrary.BookLibrary;
/// <summary>
/// Class for the collection of routes defined in this API.
/// </summary>
public static partial class ApiRoutes
{
/// <summary>
/// Routes for the Books route.
/// </summary>
public static class Books
{
public const string GET_BOOK_BY_ID = "/books/{id}";
public const string GET_BOOKS = "/books";
public const string ADD_BOOK = "/books";
}
}
@@ -1,69 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Presentation.Api.Common.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.Common;
/// <summary>
/// Base class for API controllers.
/// </summary>
[ApiController]
[ApiVersion("1.0")]
public abstract class ApiController : ControllerBase
{
/// <summary>
/// Handles controllers errors.
/// </summary>
/// <param name="errors">The error to handle.</param>
protected internal IActionResult Problem(List<Error> errors)
{
if (errors.Count is 0) // if there are no custom errors given, return a generic problem
return Problem();
// try to make the problem type more specific
if (errors.All(error => error.Type == ErrorType.Validation))
return ValidationProblem(errors);
// here we could handle custom error types, for instance: if (errors.All(error => error.NumericType == 23)), where 23 could be "domain errors"
// share the list of errors within the scope of this HTTP request
HttpContext.Items[HttpContextItemKeys.ERRORS] = errors;
// get a HTTP error status code for the selected domain error type
return Problem(errors.First());
}
/// <summary>
/// Converts an <see cref="Error"/> to a standard problem response.
/// </summary>
/// <param name="error">The error to convert.</param>
protected internal IActionResult Problem(Error error)
{
int statusCode = error.Type switch
{
ErrorType.Conflict => StatusCodes.Status409Conflict,
ErrorType.NotFound => StatusCodes.Status404NotFound,
ErrorType.Validation => StatusCodes.Status400BadRequest,
ErrorType.Failure => StatusCodes.Status403Forbidden,
_ => StatusCodes.Status500InternalServerError,
};
// return the HTTP error status and the domain error message
return Problem(statusCode: statusCode, title: error.Type.ToString(), detail: error.Description);
}
/// <summary>
/// Converts a list of <see cref="Error"/> into a standard validation problem response.
/// </summary>
/// <param name="errors">The list of errors to convert.</param>
protected internal IActionResult ValidationProblem(List<Error> errors)
{
ModelStateDictionary modelStateDictionary = new();
foreach (Error error in errors)
modelStateDictionary.AddModelError(error.Code, error.Description);
return ValidationProblem(modelStateDictionary: modelStateDictionary, title: "One or more validation errors occurred.");
}
}
@@ -1,101 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectories;
using Lumina.Application.Core.FileManagement.Directories.Queries.GetDirectoryTree;
using Lumina.Application.Core.FileManagement.Directories.Queries.GetTreeDirectories;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Common.ModelBinders;
using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.FileManagement;
/// <summary>
/// Controller for managing file system directories.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class DirectoriesController : ApiController
{
private readonly ISender _mediator;
/// <summary>
/// Initializes a new instance of the <see cref="DirectoriesController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
public DirectoriesController(ISender mediator)
{
_mediator = mediator;
}
/// <summary>
/// Gets the tree of expanded directories leading up to <paramref name="path"/>, with the additional list of drives, and children of the last child directory.
/// </summary>
/// <param name="path">The path for which to get the directory tree.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-directory-tree")]
public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetDirectoryTree([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
[FromQuery] bool includeFiles, [FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetDirectoryTreeQuery(path, includeFiles, includeHiddenElements), cancellationToken).ConfigureAwait(false);
if (!result.IsError)
{
foreach (FileSystemTreeNodeResponse treeNode in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
yield return treeNode;
}
}
}
/// <summary>
/// Gets the directories of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to get the directories.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-tree-directories")]
public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetTreeDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetTreeDirectoriesQuery(path,includeHiddenElements), cancellationToken).ConfigureAwait(false);
if (!result.IsError)
{
foreach (FileSystemTreeNodeResponse directory in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
yield return directory;
}
}
}
/// <summary>
/// Gets the directories of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to get the directories.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-directories")]
public async IAsyncEnumerable<DirectoryResponse> GetDirectories([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<DirectoryResponse>> result = await _mediator.Send(new GetDirectoriesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false);
if (!result.IsError)
{
foreach (DirectoryResponse directory in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
yield return directory;
}
}
}
}
@@ -1,43 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Core.FileManagement.Drives.Queries.GetDrives;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.FileManagement;
/// <summary>
/// Controller for managing file system drives.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class DrivesController : ApiController
{
private readonly ISender _mediator;
/// <summary>
/// Initializes a new instance of the <see cref="DrivesController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
public DrivesController(ISender mediator)
{
_mediator = mediator;
}
/// <summary>
/// Controller action for getting the list of all file system drives.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-drives")]
public async Task<IActionResult> GetDrives(CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors));
}
}
@@ -1,41 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.FileManagement.FileSystem.Queries.GetFileSystem;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.FileManagement;
/// <summary>
/// Controller for managing file systems.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/file-system")]
public class FileSystemController : ApiController
{
private readonly ISender _mediator;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
public FileSystemController(ISender mediator)
{
_mediator = mediator;
}
/// <summary>
/// Gets the type of the file system.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-type")]
public async Task<IActionResult> GetType(CancellationToken cancellationToken)
{
FileSystemTypeResponse platformType = await _mediator.Send(new GetFileSystemQuery(), cancellationToken).ConfigureAwait(false);
return Ok(platformType);
}
}
@@ -1,78 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Core.FileManagement.Files.Queries.GetFiles;
using Lumina.Application.Core.FileManagement.Files.Queries.GetTreeFiles;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Common.ModelBinders;
using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.FileManagement;
/// <summary>
/// Controller for managing file system files.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class FilesController : ApiController
{
private readonly ISender _mediator;
/// <summary>
/// Initializes a new instance of the <see cref="FilesController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
public FilesController(ISender mediator)
{
_mediator = mediator;
}
/// <summary>
/// Gets the files of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to get the files.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-tree-files")]
public async IAsyncEnumerable<FileSystemTreeNodeResponse> GetTreeFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _mediator.Send(new GetTreeFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false);
if (!result.IsError)
{
foreach (FileSystemTreeNodeResponse file in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
yield return file;
}
}
}
/// <summary>
/// Gets the files of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to get the files.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-files")]
public async IAsyncEnumerable<FileResponse> GetFiles([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path,
[FromQuery] bool includeHiddenElements, [EnumeratorCancellation] CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileResponse>> result = await _mediator.Send(new GetFilesQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false);
if (!result.IsError)
{
foreach (FileResponse file in result.Value)
{
if (cancellationToken.IsCancellationRequested)
yield break;
yield return file;
}
}
}
}
@@ -1,124 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Core.FileManagement.Paths.Commands.CombinePath;
using Lumina.Application.Core.FileManagement.Paths.Commands.SplitPath;
using Lumina.Application.Core.FileManagement.Paths.Queries.CheckPathExists;
using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathParent;
using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathRoot;
using Lumina.Application.Core.FileManagement.Paths.Queries.GetPathSeparator;
using Lumina.Application.Core.FileManagement.Paths.Queries.ValidatePath;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Common.ModelBinders;
using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.FileManagement;
/// <summary>
/// Controller for managing file system paths.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class PathController : ApiController
{
private readonly ISender _mediator;
/// <summary>
/// Initializes a new instance of the <see cref="PathController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
public PathController(ISender mediator)
{
_mediator = mediator;
}
/// <summary>
/// Gets the root of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to get the root.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-path-root")]
public async Task<IActionResult> GetPathRoot([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken)
{
ErrorOr<PathSegmentResponse> result = await _mediator.Send(new GetPathRootQuery(path), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors));
}
/// <summary>
/// Gets the path separator character of the file system.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-path-separator")]
public async Task<IActionResult> GetPathSeparator(CancellationToken cancellationToken)
{
PathSeparatorResponse result = await _mediator.Send(new GetPathSeparatorQuery(), cancellationToken).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Gets the path separator character of the file system.
/// </summary>
/// <param name="path">The path for which to get the parent path.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-path-parent")]
public async Task<IActionResult> GetPathParent([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _mediator.Send(new GetPathParentQuery(path), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors));
}
/// <summary>
/// Combines <paramref name="originalPath"/> with <paramref name="newPath"/>.
/// </summary>
/// <param name="originalPath">The path to combine to.</param>
/// <param name="newPath">The path to combine with.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("combine")]
public async Task<IActionResult> CombinePath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string originalPath, [FromQuery, ModelBinder(typeof(UrlStringBinder))] string newPath, CancellationToken cancellationToken)
{
ErrorOr<PathSegmentResponse> result = await _mediator.Send(new CombinePathCommand(originalPath, newPath), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors));
}
/// <summary>
/// Gets the path components of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path for which to get the path segments.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("split")]
public async Task<IActionResult> SplitPath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _mediator.Send(new SplitPathCommand(path), cancellationToken).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors));
}
/// <summary>
/// Validates the validity of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path to be validated.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("validate")]
public async Task<IActionResult> ValidatePath([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, CancellationToken cancellationToken)
{
PathValidResponse result = await _mediator.Send(new ValidatePathQuery(path), cancellationToken).ConfigureAwait(false);
return Ok(result);
}
/// <summary>
/// Checks whether <paramref name="path"/> exists or not.
/// </summary>
/// <param name="path">The path to be checked.</param>
/// <param name="includeHiddenElements">Whether to include hidden file system elements or not.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("check-path-exists")]
public async Task<IActionResult> CheckPathExists([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [FromQuery] bool includeHiddenElements, CancellationToken cancellationToken)
{
PathExistsResponse result = await _mediator.Send(new CheckPathExistsQuery(path, includeHiddenElements), cancellationToken).ConfigureAwait(false);
return Ok(result);
}
}
@@ -1,46 +0,0 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using Lumina.Application.Core.FileManagement.Thumbnails.Queries.GetThumbnail;
using Lumina.Contracts.Responses.FileManagement;
using Lumina.Presentation.Api.Common.ModelBinders;
using Lumina.Presentation.Api.Common.Utilities;
using Lumina.Presentation.Api.Core.Controllers.Common;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.FileManagement;
/// <summary>
/// Controller for managing file system items thumbnails.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class ThumbnailsController : ApiController
{
private readonly ISender _mediator;
/// <summary>
/// Initializes a new instance of the <see cref="ThumbnailsController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
public ThumbnailsController(ISender mediator)
{
_mediator = mediator;
}
/// <summary>
/// Gets the thumbnail of a file identified by of <paramref name="path"/>.
/// </summary>
/// <param name="path">The path of the file for which to get the thumbnail.</param>
/// <param name="quality">The quality to use for the thumbnail.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
[HttpGet("get-thumbnail")]
public async Task<IActionResult> GetThumbnail([FromQuery, ModelBinder(typeof(UrlStringBinder))] string path, [FromQuery] int quality, CancellationToken cancellationToken)
{
ErrorOr<ThumbnailResponse> getResult = await _mediator.Send(new GetThumbnailQuery(path, quality), cancellationToken);
return getResult.Match(result => File(result.Bytes, MimeTypes.GetMimeType(result.Type)), errors => Problem(errors));
}
}
@@ -1,24 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Presentation.Api.Core.Controllers.Common;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.Maintenance;
/// <summary>
/// Controller for health checks.
/// </summary>
[Route("[controller]")]
public class HealthController : ApiController
{
/// <summary>
/// Checks if the application is healthy.
/// </summary>
[HttpGet("check-health")]
public async Task<IActionResult> CheckHealth()
{
// TODO: to be implemented
return await Task.FromResult(Ok());
}
}
@@ -1,55 +0,0 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Commands.AddBook;
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Controllers.Common;
using MapsterMapper;
using Mediator;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Controllers.WrittenContentLibrary.BookLibrary.Books;
/// <summary>
/// Controller for managing books.
/// </summary>
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/[controller]")]
public class BooksController : ApiController
{
private readonly ISender _mediator;
private readonly IMapper _mapper;
/// <summary>
/// Initializes a new instance of the <see cref="BooksController"/> class.
/// </summary>
/// <param name="mediator">Injected service for mediating commands and queries.</param>
/// <param name="mapper">Injected service for mapping objects.</param>
public BooksController(ISender mediator, IMapper mapper)
{
_mediator = mediator;
_mapper = mapper;
}
/// <summary>
/// Controller action for getting the list of all books.
/// </summary>
[HttpGet()]
public async Task<IActionResult> GetBooks()
{
ErrorOr.ErrorOr<System.Collections.Generic.IEnumerable<Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Book>> result = await _mediator.Send(new GetBooksQuery()).ConfigureAwait(false);
return result.Match(result => Ok(result), errors => Problem(errors));
}
/// <summary>
/// Controller action for adding a book.
/// </summary>
/// <param name="request">The command to add a book.</param>
[HttpPost()]
public async Task<IActionResult> AddBook(AddBookRequest request)
{
ErrorOr.ErrorOr<Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate.Book> result = await _mediator.Send(_mapper.Map<AddBookCommand>(request)).ConfigureAwait(false);
return result.Match(result => Created($"/api/v1/books/{result.Id}", result), Problem);
}
}
@@ -0,0 +1,102 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Presentation.Api.Common.Http;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Common;
/// <summary>
/// Base class for API endpoints.
/// </summary>
/// <typeparam name="TRequest">The type of the request object.</typeparam>
/// <typeparam name="TResponse">The type of the response object.</typeparam>
public abstract class BaseEndpoint<TRequest, TResponse> : Endpoint<TRequest, TResponse> where TRequest : notnull
where TResponse : notnull
{
/// <summary>
/// Handles controllers errors.
/// </summary>
/// <param name="errors">The error to handle.</param>
protected IResult Problem(List<Error> errors)
{
if (errors.Count is 0) // if there are no custom errors given, return a generic problem
return Results.Problem();
// try to make the problem type more specific
if (errors.All(error => error.Type == ErrorType.Validation))
return ValidationProblem(errors);
// here we could handle custom error types, for instance: if (errors.All(error => error.NumericType == 23)), where 23 could be "domain errors"
// share the list of errors within the scope of this HTTP request
HttpContext.Items[HttpContextItemKeys.ERRORS] = errors;
// get a HTTP error status code for the selected domain error type
return Problem(errors.First());
}
/// <summary>
/// Converts an <see cref="Error"/> to a standard problem response.
/// </summary>
/// <param name="error">The error to convert.</param>
protected IResult Problem(Error error)
{
Dictionary<string, object?> extensionsDictionary = [];
int statusCode = error.Type switch
{
ErrorType.Conflict => StatusCodes.Status409Conflict,
ErrorType.NotFound => StatusCodes.Status404NotFound,
ErrorType.Validation => StatusCodes.Status400BadRequest,
ErrorType.Failure => StatusCodes.Status403Forbidden,
_ => StatusCodes.Status500InternalServerError,
};
extensionsDictionary["traceId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
// return the HTTP error status and the domain error message
return Results.Problem(
detail: error.Description,
instance: HttpContext.Request.Path,
statusCode: statusCode,
title: error.Code,
extensions: extensionsDictionary
);
}
/// <summary>
/// Converts a list of <see cref="Error"/> into a standard validation problem response.
/// </summary>
/// <param name="errors">The list of errors to convert.</param>
protected IResult ValidationProblem(List<Error> errors)
{
Dictionary<string, string[]> errorsDictionary = [];
Dictionary<string, object?> extensionsDictionary = [];
// populate the errors dictionary with error codes and their descriptions
foreach (Error error in errors)
{
if (!errorsDictionary.TryGetValue(error.Code, out string[]? value))
errorsDictionary.Add(error.Code, [error.Description]);
else
{
if (!errorsDictionary[error.Code].Contains(error.Description))
errorsDictionary[error.Code] = [.. value, error.Description];
}
}
// add trace identifier to the extensions dictionary for tracing purposes
extensionsDictionary["traceId"] = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
// return a validation problem result with the constructed error details
return Results.ValidationProblem(
errorsDictionary,
detail: "One or more validation errors occurred.",
instance: HttpContext.Request.Path,
statusCode: 422,
title: "Validation Error",
extensions: extensionsDictionary
);
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories;
/// <summary>
/// API endpoint for the <c>/directories/get-directories</c> route.
/// </summary>
public class GetDirectoriesEndpoint : BaseEndpoint<GetDirectoriesRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetDirectoriesEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Directories.GET_DIRECTORIES);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the directories of the path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the directories.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetDirectoriesRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<DirectoryResponse>> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Contracts.Responses.FileSystemManagement.Directories;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectories;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetDirectoriesEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class GetDirectoriesEndpointSummary : Summary<GetDirectoriesEndpoint, GetDirectoriesRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoriesEndpointSummary"/> class.
/// </summary>
public GetDirectoriesEndpointSummary()
{
Summary = "Retrieves the list of directories for a specified file system path.";
Description = "Returns the directories within the specified path, with an option to include hidden file system elements.";
RequestParam(r => r.Path, "The file system path for which to get the directories.");
RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not.");
Response<IEnumerable<DirectoryResponse>>(200, "The list of directories for the specified path is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree;
/// <summary>
/// API endpoint for the <c>/directories/get-directory-tree</c> route.
/// </summary>
public class GetDirectoryTreeEndpoint : BaseEndpoint<GetDirectoryTreeRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetDirectoryTreeEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Directories.GET_DIRECTORY_TREE);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the tree of expanded directories leading up to the path stored in <paramref name="request"/>, with the additional list of drives, and children of the last child directory.
/// </summary>
/// <param name="request">The request containing the file system path for for which to get the directory tree.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetDirectoryTreeRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,30 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetDirectoryTree;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetDirectoryTreeEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class GetDirectoryTreeEndpointSummary : Summary<GetDirectoryTreeEndpoint, GetDirectoryTreeRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDirectoryTreeEndpointSummary"/> class.
/// </summary>
public GetDirectoryTreeEndpointSummary()
{
Summary = "Retrieves the directory tree structure for a specified file system path.";
Description = "Returns a hierarchical view of the directory tree, with options to include files and hidden elements.";
RequestParam(r => r.Path, "The file system path for which to get the directory tree.");
RequestParam(r => r.IncludeFiles, "Whether to include files along the directories or not.");
RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not.");
Response<IEnumerable<FileSystemTreeNodeResponse>>(200, "The directory tree structure for the specified path.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories;
/// <summary>
/// API endpoint for the <c>/directories/get-tree-directories</c> route.
/// </summary>
public class GetTreeDirectoriesEndpoint : BaseEndpoint<GetTreeDirectoriesRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetTreeDirectoriesEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Directories.GET_TREE_DIRECTORIES);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the directories of the path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the directories.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetTreeDirectoriesRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Directories.GetTreeDirectories;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetTreeDirectoriesEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class GetTreeDirectoriesEndpointSummary : Summary<GetTreeDirectoriesEndpoint, GetTreeDirectoriesRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeDirectoriesEndpointSummary"/> class.
/// </summary>
public GetTreeDirectoriesEndpointSummary()
{
Summary = "Retrieves the directory tree structure for the specified file system path.";
Description = "Returns the directory tree structure, with an option to include hidden file system elements.";
RequestParam(r => r.Path, "The file system path for which to get the directory tree.");
RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not.");
Response<IEnumerable<FileSystemTreeNodeResponse>>(200, "The directory tree structure is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Core.FileSystemManagement.Drives.Queries.GetDrives;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives;
/// <summary>
/// API endpoint for the <c>/drives/get-drives</c> route.
/// </summary>
public class GetDrivesEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetDrivesEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetDrivesEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Drives.GET_DRIVES);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the list of file system drives.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sender.Send(new GetDrivesQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Drives.GetDrives;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetDrivesEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class GetDrivesEndpointSummary : Summary<GetDrivesEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetDrivesEndpointSummary"/> class.
/// </summary>
public GetDrivesEndpointSummary()
{
Summary = "Retrieves the list of file system drives.";
Description = "Returns all available drives in the file system, on Windows, or the root path, on UNIX.";
Response<IEnumerable<FileSystemTreeNodeResponse>>(200, "The list of file system drives is returned.");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
using Lumina.Application.Core.FileSystemManagement.FileSystem.Queries.GetFileSystem;
using Lumina.Contracts.Requests.FileSystemManagement.Files;
using Lumina.Contracts.Responses.FileSystemManagement.FileSystem;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem.GetType;
/// <summary>
/// API endpoint for the <c>/file-system/get-type</c> route.
/// </summary>
public class GetTypeEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetTypeEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetTypeEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.FileSystem.GET_TYPES);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the type of the file system.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
FileSystemTypeResponse platformType = await _sender.Send(new GetFileSystemQuery(), cancellationToken).ConfigureAwait(false);
return TypedResults.Ok(platformType);
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.FileSystemManagement.FileSystem;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.FileSystem.GetType;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetTypeEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class GetTypeEndpointSummary : Summary<GetTypeEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetTypeEndpointSummary"/> class.
/// </summary>
public GetTypeEndpointSummary()
{
Summary = "Gets the type of the file system.";
Description = "Returns the type of the file system.";
Response<FileSystemTypeResponse>(200, "The file system type is returned.");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
using Lumina.Contracts.Requests.FileSystemManagement.Files;
using Lumina.Contracts.Responses.FileSystemManagement.Files;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetFiles;
/// <summary>
/// API endpoint for the <c>/files/get-files</c> route.
/// </summary>
public class GetFilesEndpoint : BaseEndpoint<GetFilesRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetFilesEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Files.GET_FILES);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the files of the path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the files.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetFilesRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileResponse>> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Files;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetFiles;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetFilesEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class GetFilesEndpointSummary : Summary<GetFilesEndpoint, GetFilesRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesEndpointSummary"/> class.
/// </summary>
public GetFilesEndpointSummary()
{
Summary = "Retrieves the list of files for a specified file system path.";
Description = "Returns the files within the specified path, with an option to include hidden file system elements.";
RequestParam(r => r.Path, "The file system path for which to get the files.");
RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not.");
Response<IEnumerable<FileSystemTreeNodeResponse>>(200, "The list of files is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
using Lumina.Contracts.Requests.FileSystemManagement.Files;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles;
/// <summary>
/// API endpoint for the <c>/files/get-tree-files</c> route.
/// </summary>
public class GetTreeFilesEndpoint : BaseEndpoint<GetTreeFilesRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeFilesEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetTreeFilesEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Files.GET_TREE_FILES);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the files of the path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the files.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetTreeFilesRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<FileSystemTreeNodeResponse>> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Files;
using Lumina.Contracts.Responses.FileSystemManagement.Common;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Files.GetTreeFiles;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetTreeFilesEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class GetTreeFilesEndpointSummary : Summary<GetTreeFilesEndpoint, GetTreeFilesRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetTreeFilesEndpointSummary"/> class.
/// </summary>
public GetTreeFilesEndpointSummary()
{
Summary = "Retrieves the tree structure of files for a specified file system path.";
Description = "Returns the files within the specified path in a hierarchical tree structure, with an option to include hidden file system elements.";
RequestParam(r => r.Path, "The file system path for which to get the tree files.");
RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden file system elements or not.");
Response<IEnumerable<FileSystemTreeNodeResponse>>(200, "The tree structure of files is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists;
/// <summary>
/// API endpoint for the <c>/path/check-path-exists</c> route.
/// </summary>
public class CheckPathExistsEndpoint : BaseEndpoint<CheckPathExistsRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="CheckPathExistsEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public CheckPathExistsEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.CHECK_PATH_EXISTS);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Checks the existence of the file system path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path whose existence is checked.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(CheckPathExistsRequest request, CancellationToken cancellationToken)
{
PathExistsResponse result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return TypedResults.Ok(result);
}
}
@@ -0,0 +1,29 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using FastEndpoints.Swagger;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CheckPathExists;
/// <summary>
/// Class used for providing a textual description for the <see cref="CheckPathExistsEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class CheckPathExistsEndpointSummary : Summary<CheckPathExistsEndpoint, CheckPathExistsRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="CheckPathExistsEndpointSummary"/> class.
/// </summary>
public CheckPathExistsEndpointSummary()
{
Summary = "Checks the existence of a file system path.";
Description = "Verifies if the specified file system path exists, with an option to include hidden elements in the search.";
RequestParam(r => r.Path, "The file system path to check the exitence of.");
RequestParam(r => r.IncludeHiddenElements, "Whether to include hidden elements in the search results, or not.");
Response<PathSegmentResponse>(200, "Indicates whether the file system path exists.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath;
/// <summary>
/// API endpoint for the <c>/path/combine</c> route.
/// </summary>
public class CombinePathEndpoint : BaseEndpoint<CombinePathRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="CombinePathEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public CombinePathEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.COMBINE);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Combines the paths stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the paths to be combined.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(CombinePathRequest request, CancellationToken cancellationToken)
{
ErrorOr<PathSegmentResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.CombinePath;
/// <summary>
/// Class used for providing a textual description for the <see cref="CombinePathEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class CombinePathEndpointSummary : Summary<CombinePathEndpoint, CombinePathRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="CombinePathEndpointSummary"/> class.
/// </summary>
public CombinePathEndpointSummary()
{
Summary = "Combines two file system paths.";
Description = "Combines the specified original path with a new path to form a single file system path.";
RequestParam(r => r.OriginalPath, "The file system path to combine to.");
RequestParam(r => r.NewPath, "The file system path to combine with.");
Response<PathSegmentResponse>(200, "Successfully combined the paths.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent;
/// <summary>
/// API endpoint for the <c>/path/get-path-parent</c> route.
/// </summary>
public class GetPathParentEndpoint : BaseEndpoint<GetPathParentRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathParentEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetPathParentEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.GET_PATH_PARENT);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the parent directory of the file system path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the parent directory.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetPathParentRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathParent;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetPathParentEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class GetPathParentEndpointSummary : Summary<GetPathParentEndpoint, GetPathParentRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPathParentEndpointSummary"/> class.
/// </summary>
public GetPathParentEndpointSummary()
{
Summary = "Retrieves the parent directory of the requested file system path.";
Description = "Fetches the parent directory of a specified file system path, if available.";
RequestParam(r => r.Path, "The path for which to get the parent directory.");
Response<IEnumerable<PathSegmentResponse>>(200, "The parent directory of the requested path is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot;
/// <summary>
/// API endpoint for the <c>/path/get-path-root</c> route.
/// </summary>
public class GetPathRootEndpoint : BaseEndpoint<GetPathRootRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetPathRootEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.GET_PATH_ROOT);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the root of the file system path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the root.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetPathRootRequest request, CancellationToken cancellationToken)
{
ErrorOr<PathSegmentResponse> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathRoot;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetPathRootEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class GetPathRootEndpointSummary : Summary<GetPathRootEndpoint, GetPathRootRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPathRootEndpointSummary"/> class.
/// </summary>
public GetPathRootEndpointSummary()
{
Summary = "Retrieves a file system path root segment.";
Description = "Fetches the root segment of a specified file system path, using the provided path parameter.";
RequestParam(r => r.Path, "The file system path for which to get the root.");
Response<PathSegmentResponse>(200, "The root of the requested path is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,51 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Core.FileSystemManagement.Paths.Queries.GetPathSeparator;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator;
/// <summary>
/// API endpoint for the <c>/path/get-path-separator</c> route.
/// </summary>
public class GetPathSeparatorEndpoint : EndpointWithoutRequest<IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetPathSeparatorEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetPathSeparatorEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.GET_PATH_SEPARATOR);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the file system path separator character of the file system.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(CancellationToken cancellationToken)
{
PathSeparatorResponse result = await _sender.Send(new GetPathSeparatorQuery(), cancellationToken).ConfigureAwait(false);
return TypedResults.Ok(result);
}
}
@@ -0,0 +1,23 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.GetPathSeparator;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetPathSeparatorEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class GetPathSeparatorEndpointSummary : Summary<GetPathSeparatorEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetPathSeparatorEndpointSummary"/> class.
/// </summary>
public GetPathSeparatorEndpointSummary()
{
Summary = "Retrieves the file system path separator character.";
Description = "Fetches the path separator character for the current file system that the API is running on.";
Response<PathSeparatorResponse>(200, "The path separator character is returned.");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath;
/// <summary>
/// API endpoint for the <c>/path/split</c> route.
/// </summary>
public class SplitPathEndpoint : BaseEndpoint<SplitPathRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public SplitPathEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.SPLIT);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the path components of a file system path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path for which to get the root.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(SplitPathRequest request, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<PathSegmentResponse>> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,28 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.SplitPath;
/// <summary>
/// Class used for providing a textual description for the <see cref="SplitPathEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class SplitPathEndpointSummary : Summary<SplitPathEndpoint, SplitPathRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="SplitPathEndpointSummary"/> class.
/// </summary>
public SplitPathEndpointSummary()
{
Summary = "Splits a file system path.";
Description = "Splits a file system path into its constituent segments.";
RequestParam(r => r.Path, "The file system path for which to get the path segments.");
Response<IEnumerable<PathSegmentResponse>>(200, "Successfully split the path into segments.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath;
/// <summary>
/// API endpoint for the <c>/path/validate</c> route.
/// </summary>
public class ValidatePathEndpoint : BaseEndpoint<ValidatePathRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="ValidatePathEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public ValidatePathEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Path.VALIDATE);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Validates the validity of the file system path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path to validate.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(ValidatePathRequest request, CancellationToken cancellationToken)
{
PathValidResponse result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return TypedResults.Ok(result);
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Path;
using Lumina.Contracts.Responses.FileSystemManagement.Path;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Path.ValidatePath;
/// <summary>
/// Class used for providing a textual description for the <see cref="ValidatePathEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class ValidatePathEndpointSummary : Summary<ValidatePathEndpoint, ValidatePathRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="ValidatePathEndpointSummary"/> class.
/// </summary>
public ValidatePathEndpointSummary()
{
Summary = "Validates a file system path.";
Description = "Checks if the specified file system path is valid according to predefined criteria.";
RequestParam(r => r.Path, "The file system path to validate.");
Response<PathValidResponse>(200, "The requested path is validated.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,57 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Files;
using Lumina.Application.Common.Mapping.FileSystemManagement.Thumbnails;
using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails;
using Lumina.Contracts.Responses.FileSystemManagement.Thumbnails;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Common.Utilities;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail;
/// <summary>
/// API endpoint for the <c>/thumbnails/get-thumbnail</c> route.
/// </summary>
public class GetThumbnailEndpoint : BaseEndpoint<GetThumbnailRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetThumbnailEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetThumbnailEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Thumbnails.GET_THUMBNAIL);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the thumbnail of the file located at the path stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the file system path of the file for which to get the thumbnail.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetThumbnailRequest request, CancellationToken cancellationToken)
{
ErrorOr<ThumbnailResponse> result = await _sender.Send(request.ToQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.File(success.Bytes, MimeTypes.GetMimeType(success.Type)), Problem);
}
}
@@ -0,0 +1,27 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.FileSystemManagement.Thumbnails;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.FileSystemManagement.Thumbnails.GetThumbnail;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetThumbnailEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class GetThumbnailEndpointSummary : Summary<GetThumbnailEndpoint, GetThumbnailRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetThumbnailEndpointSummary"/> class.
/// </summary>
public GetThumbnailEndpointSummary()
{
Summary = "Retrieves a thumbnail for a specified file.";
Description = "Returns a thumbnail image for the specified file, with the option to specify the quality.";
RequestParam(r => r.Path, "The path of the file for which to get the thumbnail.");
RequestParam(r => r.Quality, "The quality to use for the thumbnail.");
Response(200, "The thumbnail image for the specified file is returned.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.FileSystemManagement.Paths;
using Lumina.Contracts.Requests.FileSystemManagement.Directories;
using Lumina.Application.Common.Mapping.FileSystemManagement.Directories;
using Lumina.Contracts.Responses.FileSystemManagement;
using Lumina.Presentation.Api.Common.Routes.FileSystemManagement;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.Maintenance;
/// <summary>
/// API endpoint for the <c>/directories/get-directories</c> route.
/// </summary>
public class CheckHealthEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="CheckHealthEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public CheckHealthEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Health.CHECK_HEALTH);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gwts the health status of the backend system.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
// TODO: to be implemented
return await Task.FromResult(TypedResults.Ok());
}
}
@@ -0,0 +1,55 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Presentation.Api.Common.Routes.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.AddBook;
/// <summary>
/// API endpoint for the <c>/books</c> route.
/// </summary>
public class AddBookEndpoint : BaseEndpoint<AddBookRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="AddBookEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public AddBookEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.POST);
Routes(ApiRoutes.Books.ADD_BOOK);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Adds a book stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the book to be added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(AddBookRequest request, CancellationToken cancellationToken)
{
ErrorOr<BookResponse> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Created($"{BaseURL}api/v1{ApiRoutes.Books.ADD_BOOK}/{result.Value.Id}", result.Value), Problem);
}
}
@@ -0,0 +1,50 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.AddBook;
/// <summary>
/// Class used for providing a textual description for the <see cref="AddBookEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class AddBookEndpointSummary : Summary<AddBookEndpoint, AddBookRequest>
{
/// <summary>
/// Initializes a new instance of the <see cref="AddBookEndpointSummary"/> class.
/// </summary>
public AddBookEndpointSummary()
{
Summary = "Adds a new book.";
Description = "Creates a new book and returns its details, including the location of the newly created resource.";
RequestParam(r => r.Metadata, "Written content metadata of the book.");
RequestParam(r => r.Metadata!.Title, "The title of the written content.");
RequestParam(r => r.Format, "The format of the book (e.g., Hardcover, Paperback), if applicable.");
RequestParam(r => r.Edition, "The edition of the book, if applicable.");
RequestParam(r => r.VolumeNumber, "The volume or book number in the series, if applicable.");
RequestParam(r => r.Series, "The series name, if the book is part of a series.");
RequestParam(r => r.ASIN, "The ASIN (Amazon Standard Identification Number) of the book, if applicable.");
RequestParam(r => r.GoodreadsId, "The Goodreads ID of the book, if applicable.");
RequestParam(r => r.LCCN, "The Library of Congress Control Number (LCCN) of the book, if applicable.");
RequestParam(r => r.OCLCNumber, "The OCLC Number (WorldCat identifier) of the book, if applicable.");
RequestParam(r => r.OpenLibraryId, "The Open Library ID of the book, if applicable.");
RequestParam(r => r.LibraryThingId, "The LibraryThing ID of the book, if applicable.");
RequestParam(r => r.GoogleBooksId, "The Google Books ID of the book, if applicable.");
RequestParam(r => r.BarnesAndNobleId, "The Barnes & Noble ID of the book, if applicable.");
RequestParam(r => r.AppleBooksId, "The Apple Books ID of the book, if applicable.");
RequestParam(r => r.ISBNs, "The list of ISBN (International Standard Book Number) of the book.");
RequestParam(r => r.Contributors, "The list of media contributors (actors, directors, etc) starring in this book.");
RequestParam(r => r.Ratings, "The list of ratings for this book.");
ResponseParam<BookResponse>(r => r.Id, "The unique identifier of the entity.");
ResponseParam<BookResponse>(r => r.Created, "The date and time when the entity was created.");
ResponseParam<BookResponse>(r => r.Updated, "The date and time when the entity was last updated.");
ResponseParam<BookResponse>(r => r.Metadata, "The written content metadata of the book.");
ResponseParam<BookResponse>(r => r.Metadata.Title, "The title of the media item.");
ResponseParam<BookResponse>(r => r.Metadata.OriginalTitle, "The original title of the media item.");
Response<BookResponse>(201, "The book was successfully created.", "The location of the created resource is provided in the Location header.");
Response<ProblemDetails>(422, "The request did not pass validation checks.", "application/problem+json");
}
}
@@ -0,0 +1,54 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Core.WrittenContentLibrary.BooksLibrary.Books.Queries.GetBooks;
using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Presentation.Api.Common.Routes.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.GetBooks;
/// <summary>
/// API endpoint for the <c>/books</c> route.
/// </summary>
public class GetBooksEndpoint : BaseEndpoint<EmptyRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetBooksEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Books.GET_BOOKS);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Gets the list of all books.
/// </summary>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(EmptyRequest _, CancellationToken cancellationToken)
{
ErrorOr<IEnumerable<BookResponse>> result = await _sender.Send(new GetBooksQuery(), cancellationToken).ConfigureAwait(false);
return result.Match(success => TypedResults.Ok(success), Problem);
}
}
@@ -0,0 +1,24 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using Lumina.Contracts.Responses.WrittenContentLibrary.BookLibrary.Books;
using System.Collections.Generic;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.WrittenContentLibrary.BookLibrary.Books.GetBooks;
/// <summary>
/// Class used for providing a textual description for the <see cref="GetBooksEndpoint"/> API endpoint, for Swagger.
/// </summary>
public class GetBooksEndpointSummary : Summary<GetBooksEndpoint>
{
/// <summary>
/// Initializes a new instance of the <see cref="GetBooksEndpointSummary"/> class.
/// </summary>
public GetBooksEndpointSummary()
{
Summary = "Retrieves the list of books.";
Description = "Returns the entire list of books.";
Response<IEnumerable<BookResponse>>(200, "The list of books is returned.");
}
}
@@ -0,0 +1,56 @@
#region ========================================================================= USING =====================================================================================
using ErrorOr;
using FastEndpoints;
using Lumina.Application.Common.Mapping.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Contracts.Requests.WrittenContentLibrary.BookLibrary.Books;
using Lumina.Domain.Core.Aggregates.WrittenContentLibrary.BookLibraryAggregate;
using Lumina.Presentation.Api.Common.Routes.WrittenContentLibrary.BookLibrary;
using Lumina.Presentation.Api.Core.Endpoints.Common;
using Mediator;
using Microsoft.AspNetCore.Http;
using System.Threading;
using System.Threading.Tasks;
#endregion
namespace Lumina.Presentation.Api.Core.Endpoints.WrittenContentLibrary.BookLibrary.GetBook;
/// <summary>
/// API endpoint for the <c>/books</c> route.
/// </summary>
public class GetBookEndpoint : BaseEndpoint<GetBookRequest, IResult>
{
private readonly ISender _sender;
/// <summary>
/// Initializes a new instance of the <see cref="GetBookEndpoint"/> class.
/// </summary>
/// <param name="sender">Injected service for mediating commands and queries.</param>
public GetBookEndpoint(ISender sender)
{
_sender = sender;
}
/// <summary>
/// Configures the API endpoint.
/// </summary>
public override void Configure()
{
Verbs(Http.GET);
Routes(ApiRoutes.Books.GET_BOOK_BY_ID);
Version(1);
AllowAnonymous();
DontCatchExceptions();
}
/// <summary>
/// Adds a book stored in <paramref name="request"/>.
/// </summary>
/// <param name="request">The request containing the book to be added.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
public override async Task<IResult> ExecuteAsync(GetBookRequest request, CancellationToken cancellationToken)
{
//ErrorOr<Book> result = await _sender.Send(request.ToCommand(), cancellationToken).ConfigureAwait(false);
//return result.Match(success => TypedResults.CreatedAtRoute($"/api/v1/books/{success.Id}", success), Problem);
return await Task.FromResult(TypedResults.Ok());
}
}
@@ -18,18 +18,14 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="Mapster" Version="7.4.0" />
<PackageReference Include="Mapster.DependencyInjection" Version="1.0.1" />
<PackageReference Include="FastEndpoints" Version="5.30.0" />
<PackageReference Include="FastEndpoints.Swagger" Version="5.30.0" />
<PackageReference Include="Mediator.Abstractions" Version="2.1.7" />
<PackageReference Include="Mediator.SourceGenerator" Version="2.1.7">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Versioning.ApiExplorer" Version="5.1.0" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="8.0.8" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.21.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.7.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.8">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
+14 -10
View File
@@ -1,11 +1,12 @@
#region ========================================================================= USING =====================================================================================
using FastEndpoints;
using FastEndpoints.Swagger;
using Lumina.Application.Common.DependencyInjection;
using Lumina.DataAccess.Common.DependencyInjection;
using Lumina.Domain.Common.DependencyInjection;
using Lumina.Infrastructure.Common.DependencyInjection;
using Lumina.Presentation.Api.Common.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;
#endregion
@@ -37,18 +38,21 @@ public class Program
app.UseCors("AllowAll");
app.UseExceptionHandler("/error"); // uses a middleware which reexecutes the request to the error path
// configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
//app.UseExceptionHandler("/error"); // uses a middleware which re-executes the request to the error path
//app.UseHttpsRedirection();
app.MapControllers();
app.UseAuthorization();
app.UseFastEndpoints(config =>
{
config.Endpoints.RoutePrefix = "api";
config.Versioning.Prefix = "v";
config.Versioning.DefaultVersion = 1;
config.Versioning.PrependToRoute = true;
config.Endpoints.ShortNames = true;
});
app.UseSwaggerGen();
await app.RunAsync().ConfigureAwait(false);
}