Skip to content

Option to generate x-enum-varnames and x-enum-descriptionsΒ #63223

@johnkwaters

Description

@johnkwaters

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe the problem.

Scalar supports these now, and if I add this custom transformer

      srv.AddOpenApi(options => {
            options.AddSchemaTransformer<EnumSchemaTransformer>();
        });

internal sealed class EnumSchemaTransformer : IOpenApiSchemaTransformer
{
    public Task TransformAsync(OpenApiSchema schema, OpenApiSchemaTransformerContext context, CancellationToken cancellationToken)
    {
        var type = context.JsonTypeInfo?.Type;

        if (type != null && type.IsEnum)
        {
            var enumValues = Enum.GetValues(type).Cast<object>();
            var enumNames = Enum.GetNames(type);

            var openApiValues = new OpenApiArray();
            var openApiNames = new OpenApiArray();
            var openApiDescriptions = new OpenApiArray();

            foreach (var value in enumValues)
            {
                openApiValues.Add(new OpenApiInteger((int)value));
            }

            foreach (var name in enumNames)
            {
                openApiNames.Add(new OpenApiString(name));

                var field = type.GetField(name);
                var description = field?.GetCustomAttribute<DescriptionAttribute>()?.Description ?? string.Empty;
                if (!string.IsNullOrEmpty(description))
                {
                    openApiDescriptions.Add(new OpenApiString(description));
                }
            }

            schema.Enum = openApiValues;
            schema.Extensions["x-enum-varnames"] = openApiNames;
            if (openApiDescriptions.Any())
            {
                schema.Extensions["x-enum-descriptions"] = openApiDescriptions;
            }
        }

        return Task.CompletedTask;
    }
}

It looks great:

Image

Maybe this transform can be included by default or with an option?

Describe the solution you'd like

Maybe this transform can be included by default or with an option?

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcfeature-openapi

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions