| | 1 | | using System.Reflection; |
| | 2 | | using Microsoft.OpenApi.Models; |
| | 3 | | using Swashbuckle.AspNetCore.SwaggerGen; |
| | 4 | |
|
| | 5 | | namespace Syki.Back.Filters; |
| | 6 | |
|
| | 7 | | public class ExamplesOperationsFilterFilter : IOperationFilter |
| | 8 | | { |
| | 9 | | public void Apply(OpenApiOperation operation, OperationFilterContext context) |
| | 10 | | { |
| 0 | 11 | | var method = context.MethodInfo; |
| | 12 | |
|
| 0 | 13 | | var swaggerAttrs = method |
| 0 | 14 | | .GetCustomAttributes<SwaggerResponseExampleAttribute>(inherit: false); |
| | 15 | |
|
| 0 | 16 | | foreach (var attr in swaggerAttrs) |
| | 17 | | { |
| 0 | 18 | | var providerType = attr.ExamplesProviderType; |
| 0 | 19 | | var responseType = GetExampleGenericType(providerType); |
| 0 | 20 | | var statusCode = attr.StatusCode.ToString(); |
| | 21 | |
|
| 0 | 22 | | if (responseType == null) |
| | 23 | | continue; |
| | 24 | |
|
| 0 | 25 | | if (!operation.Responses.ContainsKey(statusCode)) |
| | 26 | | { |
| 0 | 27 | | operation.Responses[statusCode] = new OpenApiResponse |
| 0 | 28 | | { |
| 0 | 29 | | Description = GetDefaultDescription(statusCode), |
| 0 | 30 | | Content = new Dictionary<string, OpenApiMediaType>() |
| 0 | 31 | | }; |
| | 32 | | } |
| | 33 | |
|
| 0 | 34 | | var schema = context.SchemaGenerator.GenerateSchema(responseType, context.SchemaRepository); |
| 0 | 35 | | operation.Responses[statusCode].Content["application/json"] = new OpenApiMediaType |
| 0 | 36 | | { |
| 0 | 37 | | Schema = schema |
| 0 | 38 | | }; |
| | 39 | | } |
| 0 | 40 | | } |
| | 41 | |
|
| | 42 | | private static Type? GetExampleGenericType(Type providerType) |
| | 43 | | { |
| 0 | 44 | | return providerType |
| 0 | 45 | | .GetInterfaces() |
| 0 | 46 | | .FirstOrDefault(i => |
| 0 | 47 | | i.IsGenericType && |
| 0 | 48 | | i.GetGenericTypeDefinition() == typeof(IMultipleExamplesProvider<>)) |
| 0 | 49 | | ?.GetGenericArguments()[0]; |
| | 50 | | } |
| | 51 | |
|
| 0 | 52 | | private string GetDefaultDescription(string statusCode) => statusCode switch |
| 0 | 53 | | { |
| 0 | 54 | | "200" => "Success", |
| 0 | 55 | | "400" => "Bad Request", |
| 0 | 56 | | "401" => "Unauthorized", |
| 0 | 57 | | "403" => "Forbidden", |
| 0 | 58 | | "404" => "Not Found", |
| 0 | 59 | | _ => "Response" |
| 0 | 60 | | }; |
| | 61 | | } |