fabien0102 / openapi-codegen

A tool for generating code base on an OpenAPI schema.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Handling of enums

PeterKottas opened this issue · comments

Given an API specification like this:

"OrderByEnum": {
        "enum": [
          1,
          2
        ],
        "type": "integer",
        "description": "\r\n* **1** - Ascending\r\n* **2** - Descending\r\n\n\n1 = Ascending\n\n2 = Descending",
        "format": "int32",
        "x-enumNames": [
          "Ascending",
          "Descending"
        ]
      }

Currently, the generated type ends up being:

/**
 * * **1** - Ascending
 * * **2** - Descending
 *
 *
 * 1 = Ascending
 *
 * 2 = Descending
 *
 * @format int32
 */
export type OrderByEnum = 1 | 2;

Taking advantage of the x-enumNames, we could actually create a more desirable output like:

export enum OrderByEnum {
    Ascending = 1,
    Descending = 2,
}

This is something that NSwagStudio does, it's universally supported, e.g. https://github.com/unchase/Unchase.Swashbuckle.AspNetCore.Extensions search for AddEnumsWithValuesFixFilters.
The biggest problem (other than convenience) arises when you want to use the enum in the flag. In the previous code, with enum I could do:

const test = OrderByEnum.Ascending | OrderByEnum.Descending;

Which is valid, and also in many cases desirable, meanwhile with the current code:

const test:  OrderByEnum = 3;

Will not work because 3 is not allowed by the union type.

I agree with OP that generating enums based on the spec would be nice. I migrated from ferdikoomen/openapi-typescript-codegen, which generates enums by default with union types being an optional feature.

@PeterKottas @LoukaOctave I added this feat, check it out:
#153