From e1ae84bffc52b69b9723f552f7c95598f2105e72 Mon Sep 17 00:00:00 2001 From: ZaqueuCavalcante Date: Sun, 24 Nov 2024 16:30:16 -0300 Subject: [PATCH] Add HttpMethodSorterDocumentFilter --- Back/Configs/DocsConfigs.cs | 1 + Back/Filters/AuthOperationsFilter.cs | 1 - .../Filters/HttpMethodSorterDocumentFilter.cs | 50 +++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 Back/Filters/HttpMethodSorterDocumentFilter.cs diff --git a/Back/Configs/DocsConfigs.cs b/Back/Configs/DocsConfigs.cs index a00e70d0..1d40668f 100644 --- a/Back/Configs/DocsConfigs.cs +++ b/Back/Configs/DocsConfigs.cs @@ -39,6 +39,7 @@ public static void AddDocsConfigs(this IServiceCollection services) options.DocInclusionPredicate((name, api) => true); options.OperationFilter(); + options.DocumentFilter(); options.ExampleFilters(); diff --git a/Back/Filters/AuthOperationsFilter.cs b/Back/Filters/AuthOperationsFilter.cs index 74fcdec1..76559fd3 100644 --- a/Back/Filters/AuthOperationsFilter.cs +++ b/Back/Filters/AuthOperationsFilter.cs @@ -1,7 +1,6 @@ using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using Microsoft.AspNetCore.Mvc.Controllers; -using Syki.Back.Features.Cross.SkipUserRegister; namespace Syki.Back.Filters; diff --git a/Back/Filters/HttpMethodSorterDocumentFilter.cs b/Back/Filters/HttpMethodSorterDocumentFilter.cs new file mode 100644 index 00000000..20f45f5a --- /dev/null +++ b/Back/Filters/HttpMethodSorterDocumentFilter.cs @@ -0,0 +1,50 @@ +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +namespace Syki.Back.Filters; + +public class HttpMethodSorterDocumentFilter : IDocumentFilter +{ + public void Apply(OpenApiDocument document, DocumentFilterContext context) + { + // Order path groups (OpenApiPathItems) alphabetically + var pathKvps = document.Paths + .OrderBy(pathKvp => + { + if (pathKvp.Value.Operations.Any(x => x.Key == OperationType.Post)) return 10; + if (pathKvp.Value.Operations.Any(x => x.Key == OperationType.Get)) return 20; + if (pathKvp.Value.Operations.Any(x => x.Key == OperationType.Put)) return 30; + if (pathKvp.Value.Operations.Any(x => x.Key == OperationType.Delete)) return 40; + return 50; + }) + .ToList(); + + document.Paths.Clear(); + pathKvps.ForEach(kvp => document.Paths.Add(kvp.Key, kvp.Value)); + + // Order operations by method within each group + document.Paths.ToList().ForEach(pathKvp => + { + var operationKvps = pathKvp.Value.Operations + .OrderBy(kvp => + { + var weight = kvp.Key switch + { + OperationType.Post => 10, + OperationType.Get => 20, + OperationType.Put => 30, + OperationType.Delete => 40, + _ => 50, + }; + return weight; + }) + .ToList(); + + pathKvp.Value.Operations.Clear(); + operationKvps.ForEach(operationKvp => + { + pathKvp.Value.Operations.Add(operationKvp); + }); + }); + } +}