-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSimplifyWebDocumentFilter.cs
More file actions
184 lines (151 loc) · 5.06 KB
/
Copy pathSimplifyWebDocumentFilter.cs
File metadata and controls
184 lines (151 loc) · 5.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
using System;
using System.Collections.Generic;
using System.Linq;
using Simplify.Web.Controllers.Meta.Routing;
using Swashbuckle.AspNetCore.SwaggerGen;
using Microsoft.OpenApi;
using JsonNode = System.Text.Json.Nodes.JsonNode;
namespace Simplify.Web.Swagger;
/// <summary>
/// Provides the Swagger <see cref="IDocumentFilter" /> implementation for Simplify.Web framework.
/// </summary>
/// <seealso cref="IDocumentFilter" />
public class SimplifyWebDocumentFilter : IDocumentFilter
{
private readonly SimplifyWebSwaggerArgs? _args;
/// <summary>
/// Initializes an instance of <see cref="SimplifyWebDocumentFilter" />.
/// </summary>
public SimplifyWebDocumentFilter() { }
/// <summary>
/// Initializes an instance of <see cref="SimplifyWebDocumentFilter" />.
/// </summary>
/// <param name="args">The registration args</param>
public SimplifyWebDocumentFilter(SimplifyWebSwaggerArgs? args) => _args = args;
/// <summary>
/// Applies current filter
/// </summary>
/// <param name="swaggerDoc">The Open API document</param>
/// <param name="context">The context</param>
public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var controllerActions = ControllerActionsFactory
.CreateControllerActionsFromControllersMetaData(context)
.ToList();
foreach (
var item in controllerActions
.GroupBy(x => x.Path)
.Select(x => new KeyValuePair<string, OpenApiPathItem>(
x.Key,
CreatePathItem(x, swaggerDoc, context)
))
)
swaggerDoc.Paths.Add(item.Key, item.Value);
PopulateDocumentTags(swaggerDoc, controllerActions);
}
private static IList<IOpenApiParameter> CreateParameters(ControllerAction item, DocumentFilterContext context) =>
item.ControllerRoute.Items
.OfType<PathParameter>()
.Select(x => (IOpenApiParameter)CreatePathParameter(x, item, context))
.ToList();
private static OpenApiParameter CreatePathParameter(PathParameter pathParam, ControllerAction item, DocumentFilterContext context)
{
var param = new OpenApiParameter
{
Name = pathParam.Name,
In = ParameterLocation.Path,
Required = true,
AllowEmptyValue = false,
};
if (item.RouteParameterTypes.TryGetValue(pathParam.Name, out var type))
param.Schema = context.SchemaGenerator.GenerateSchema(type, context.SchemaRepository);
return param;
}
private OpenApiPathItem CreatePathItem(
IEnumerable<ControllerAction> actions,
OpenApiDocument swaggerDoc,
DocumentFilterContext context
)
{
var pathItem = new OpenApiPathItem();
foreach (var item in actions)
pathItem.AddOperation(item.Type, CreateOperation(item, swaggerDoc, context));
return pathItem;
}
private OpenApiOperation CreateOperation(ControllerAction item, OpenApiDocument swaggerDoc, DocumentFilterContext context)
{
var operation = new OpenApiOperation();
operation.Tags ??= new HashSet<OpenApiTagReference>();
operation.Tags.Add(new OpenApiTagReference(item.Names.GroupName));
if (item.Names.Summary != null)
operation.Summary = item.Names.Summary;
foreach (var response in item.Responses)
{
operation.Responses ??= new OpenApiResponses();
operation.Responses.Add(response.Key.ToString(), response.Value);
}
operation.Parameters = CreateParameters(item, context);
if (item.RequestBody.Content is { Count: > 0 })
operation.RequestBody = item.RequestBody;
if (item.IsAuthorizationRequired)
{
var schemeNames = ResolveSecuritySchemeNames(swaggerDoc);
if (schemeNames.Count > 0)
operation.Security = schemeNames
.Select(name => new OpenApiSecurityRequirement
{
[new OpenApiSecuritySchemeReference(name, swaggerDoc)] = [],
})
.ToList();
}
if (_args == null)
return operation;
foreach (var parameter in _args.Parameters)
operation.Parameters.Add(parameter);
if (_args.AcceptLanguageHeader is { } acceptLang)
operation.Parameters.Add(CreateAcceptLanguageParameter(acceptLang));
return operation;
}
private IReadOnlyList<string> ResolveSecuritySchemeNames(OpenApiDocument swaggerDoc)
{
if (_args?.SecuritySchemeName is { } explicitName)
return [explicitName];
return swaggerDoc.Components?.SecuritySchemes?.Keys?.ToList() ?? [];
}
private static OpenApiParameter CreateAcceptLanguageParameter(AcceptLanguageHeaderArgs args)
{
var param = new OpenApiParameter
{
Name = "Accept-Language",
In = ParameterLocation.Header,
Description = "Language preference for the response.",
Required = true,
AllowEmptyValue = true,
};
param.Example = args.Default;
param.Schema = new OpenApiSchema
{
Default = args.Default,
Enum = args.Languages.Select(l => (JsonNode)l).ToList()
};
return param;
}
private static void PopulateDocumentTags(
OpenApiDocument swaggerDoc,
IEnumerable<ControllerAction> actions
)
{
var existingNames =
swaggerDoc.Tags?.Select(t => t.Name).ToHashSet(StringComparer.Ordinal) ?? [];
foreach (
var name in actions
.Select(x => x.Names.GroupName)
.Distinct()
.Where(n => !existingNames.Contains(n))
)
{
swaggerDoc.Tags ??= new HashSet<OpenApiTag>();
swaggerDoc.Tags.Add(new OpenApiTag { Name = name });
}
}
}