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";
}
}