< Summary - Syki

Information
Class: Syki.Back.Filters.ExamplesOperationsFilterFilter
Assembly: Back
File(s): /home/runner/work/syki/syki/Back/Filters/ExamplesOperationsFilterFilter.cs
Tag: 4_16869239191
Line coverage
0%
Covered lines: 0
Uncovered lines: 35
Coverable lines: 35
Total lines: 61
Line coverage: 0%
Branch coverage
0%
Covered branches: 0
Total branches: 20
Branch coverage: 0%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
Apply(...)0%4260%
GetExampleGenericType(...)0%2040%
GetDefaultDescription(...)0%110100%

File(s)

/home/runner/work/syki/syki/Back/Filters/ExamplesOperationsFilterFilter.cs

#LineLine coverage
 1using System.Reflection;
 2using Microsoft.OpenApi.Models;
 3using Swashbuckle.AspNetCore.SwaggerGen;
 4
 5namespace Syki.Back.Filters;
 6
 7public class ExamplesOperationsFilterFilter : IOperationFilter
 8{
 9    public void Apply(OpenApiOperation operation, OperationFilterContext context)
 10    {
 011        var method = context.MethodInfo;
 12
 013        var swaggerAttrs = method
 014            .GetCustomAttributes<SwaggerResponseExampleAttribute>(inherit: false);
 15
 016        foreach (var attr in swaggerAttrs)
 17        {
 018            var providerType = attr.ExamplesProviderType;
 019            var responseType = GetExampleGenericType(providerType);
 020            var statusCode = attr.StatusCode.ToString();
 21
 022            if (responseType == null)
 23                continue;
 24
 025            if (!operation.Responses.ContainsKey(statusCode))
 26            {
 027                operation.Responses[statusCode] = new OpenApiResponse
 028                {
 029                    Description = GetDefaultDescription(statusCode),
 030                    Content = new Dictionary<string, OpenApiMediaType>()
 031                };
 32            }
 33
 034            var schema = context.SchemaGenerator.GenerateSchema(responseType, context.SchemaRepository);
 035            operation.Responses[statusCode].Content["application/json"] = new OpenApiMediaType
 036            {
 037                Schema = schema
 038            };
 39        }
 040    }
 41
 42    private static Type? GetExampleGenericType(Type providerType)
 43    {
 044        return providerType
 045            .GetInterfaces()
 046            .FirstOrDefault(i =>
 047                i.IsGenericType &&
 048                i.GetGenericTypeDefinition() == typeof(IMultipleExamplesProvider<>))
 049            ?.GetGenericArguments()[0];
 50    }
 51
 052    private string GetDefaultDescription(string statusCode) => statusCode switch
 053    {
 054        "200" => "Success",
 055        "400" => "Bad Request",
 056        "401" => "Unauthorized",
 057        "403" => "Forbidden",
 058        "404" => "Not Found",
 059        _ => "Response"
 060    };
 61}