| | 1 | | using Microsoft.OpenApi.Models; |
| | 2 | | using Swashbuckle.AspNetCore.SwaggerGen; |
| | 3 | |
|
| | 4 | | namespace Syki.Back.Filters; |
| | 5 | |
|
| | 6 | | public class HttpMethodSorterDocumentFilter : IDocumentFilter |
| | 7 | | { |
| | 8 | | public void Apply(OpenApiDocument document, DocumentFilterContext context) |
| | 9 | | { |
| | 10 | | // Order path groups (OpenApiPathItems) alphabetically |
| 0 | 11 | | var pathKvps = document.Paths |
| 0 | 12 | | .OrderBy(pathKvp => |
| 0 | 13 | | { |
| 0 | 14 | | if (pathKvp.Value.Operations.Any(x => x.Key == OperationType.Post)) return 10; |
| 0 | 15 | | if (pathKvp.Value.Operations.Any(x => x.Key == OperationType.Get)) return 20; |
| 0 | 16 | | if (pathKvp.Value.Operations.Any(x => x.Key == OperationType.Put)) return 30; |
| 0 | 17 | | if (pathKvp.Value.Operations.Any(x => x.Key == OperationType.Delete)) return 40; |
| 0 | 18 | | return 50; |
| 0 | 19 | | }) |
| 0 | 20 | | .ToList(); |
| | 21 | |
|
| 0 | 22 | | document.Paths.Clear(); |
| 0 | 23 | | pathKvps.ForEach(kvp => document.Paths.Add(kvp.Key, kvp.Value)); |
| | 24 | |
|
| | 25 | | // Order operations by method within each group |
| 0 | 26 | | document.Paths.ToList().ForEach(pathKvp => |
| 0 | 27 | | { |
| 0 | 28 | | var operationKvps = pathKvp.Value.Operations |
| 0 | 29 | | .OrderBy(kvp => |
| 0 | 30 | | { |
| 0 | 31 | | var weight = kvp.Key switch |
| 0 | 32 | | { |
| 0 | 33 | | OperationType.Post => 10, |
| 0 | 34 | | OperationType.Get => 20, |
| 0 | 35 | | OperationType.Put => 30, |
| 0 | 36 | | OperationType.Delete => 40, |
| 0 | 37 | | _ => 50, |
| 0 | 38 | | }; |
| 0 | 39 | | return weight; |
| 0 | 40 | | }) |
| 0 | 41 | | .ToList(); |
| 0 | 42 | |
|
| 0 | 43 | | pathKvp.Value.Operations.Clear(); |
| 0 | 44 | | operationKvps.ForEach(operationKvp => |
| 0 | 45 | | { |
| 0 | 46 | | pathKvp.Value.Operations.Add(operationKvp); |
| 0 | 47 | | }); |
| 0 | 48 | | }); |
| 0 | 49 | | } |
| | 50 | | } |