Skip to content

Commit

Permalink
Add HttpMethodSorterDocumentFilter
Browse files Browse the repository at this point in the history
  • Loading branch information
ZaqueuCavalcante committed Nov 24, 2024
1 parent b073e5d commit e1ae84b
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
1 change: 1 addition & 0 deletions Back/Configs/DocsConfigs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public static void AddDocsConfigs(this IServiceCollection services)
options.DocInclusionPredicate((name, api) => true);

options.OperationFilter<AuthOperationsFilter>();
options.DocumentFilter<HttpMethodSorterDocumentFilter>();

options.ExampleFilters();

Expand Down
1 change: 0 additions & 1 deletion Back/Filters/AuthOperationsFilter.cs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down
50 changes: 50 additions & 0 deletions Back/Filters/HttpMethodSorterDocumentFilter.cs
Original file line number Diff line number Diff line change
@@ -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);
});
});
}
}

0 comments on commit e1ae84b

Please sign in to comment.