RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.61k stars 1.22k forks source link

Generate OpenApi 3.1 compatible Enums? #4839

Open JohnGalt1717 opened 3 months ago

JohnGalt1717 commented 3 months ago

Hi, is it possible to generate enaums like this: https://stackoverflow.com/questions/66465888/how-to-define-enum-mapping-in-openapi ?

I can't find any documentation on how to enable it, but I need 3.1 compatibility with the oneOf syntax.

RicoSuter commented 3 months ago

You can implement your own ISchemaProcessor and transform all enum schemas to OAI 3.1 enum schemas

JohnGalt1717 commented 3 months ago

OK, thanks.

Is there any plans to add this natively?

JohnGalt1717 commented 3 months ago

PS for anyone that needs it, here's quick and dirty standards compliant enum Schema Processor.

public sealed class FixNSwagEnumsProcessor : ISchemaProcessor {
    public void Process(SchemaProcessorContext context) {
        if (!context.ContextualType.Type.IsEnum)
            return;

        foreach(var item in context.Schema.EnumerationNames.Index()) {
            var enumValue = context.Schema.Enumeration.ElementAt(item.index);
            var enumSchema = new JsonSchema
            {
                ExtensionData = new Dictionary<string, object?>
                {
                    { "const", enumValue },
                    { "title", item.item }
                }
            };

            context.Schema.OneOf.Add(enumSchema);           
        }
    }
}