Manweill / swagger-axios-codegen

swagger client to use axios and typescript
MIT License
306 stars 83 forks source link

fix: numeric enum keys are always prefixed with `KEY_` #114

Closed vilyus closed 4 years ago

vilyus commented 4 years ago

relates to https://github.com/Manweill/swagger-axios-codegen/pull/65

Problem: spec definition contained the following schema:

{
  "ReportSchema": {
    "properties": {
      "errorCode": {
        "description": "Error code",
        "enum": [
          "10",
          "20",
          "30",
          "40"
        ],
        "example": "10",
        "maxLength": 3,
        "type": "string"
      }
    }
  }
}

The output was not a valid TS:

export enum ReportSchemaErrorCode {
  '10' = '10',
  '20' = '20',
  '30' = '30',
  '40' = '40'
}

Enum keys in TS cannot be numeric.

The PR#65 fixed one of the 4 places with the enum generation. This PR fixes the other three places.

Output with this PR:

export enum ReportSchemaErrorCode {
  'KEY_10' = '10',
  'KEY_20' = '20',
  'KEY_30' = '30',
  'KEY_40' = '40'
}
Manweill commented 4 years ago

The numeric enums always generate type not enum.

vilyus commented 4 years ago

By numeric I mean "enum": ["10", "20", "30"], "type": "string" where enum values happen to start with digits.

Currently rendering the following schema with the master branch produces invalid TS:

{
  "openapi": "3.0.0",
  "info": {
    "title": "Sample",
    "description": "Foobar",
    "version": "0.1"
  },
  "paths": {},
  "components": {
    "schemas": {
      "ReportSchema": {
        "properties": {
          "errorCode": {
            "description": "Error code",
            "enum": [
              "10",
              "20",
              "30",
              "40"
            ],
            "example": "10",
            "maxLength": 3,
            "type": "string"
          }
        }
      }
    }
  }
}

Generated output:

// ... snip
export enum EnumReportSchemaErrorCode {
  '10' = '10',
  '20' = '20',
  '30' = '30',
  '40' = '40'
}

Unfortunately tsc considers such an enum to contain errors: An enum member cannot have a numeric name.

Manweill commented 4 years ago

@vilyus in your spec,why your type is not number/int32

vilyus commented 4 years ago

I have a legacy spec that I cannot change. The other failing example would be (I can imagine a scheme like that in a real project, and it cannot be changed to number/int32):

"enum": ["10", "20", "unset"], "type": "string"

Manweill commented 4 years ago

I got it.