cyclosproject / ng-openapi-gen

An OpenAPI 3.0 codegen for Angular
MIT License
397 stars 132 forks source link

Generate enums as string literal #320

Closed detomarco closed 4 months ago

detomarco commented 5 months ago

Version: 0.51.0

Schema

openapi: 3.0.1
info:
  title: example
  version: 0.0.1
paths:
  /cars:
    get:
      operationId: me
      responses:
        "200":
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Cars'
          description: OK
components:
  schemas:
    Cars:
      type: object
      properties:
        types:
          type: string
          enum:
            - FERRARI
            - FORD
            - BMW

Command

ng-openapi-gen  --input {input} --output {output}

Current output

export interface Cars {
  types?: 'FERRARI' | 'FORD' | 'BMW';
}

Desired output

export type CarsType = 'FERRARI' | 'FORD' | 'BMW'
export interface Cars {
  types?: CarsType;
}

As described above, I'd like to have the option to generate enums as String literals, so I could reuse CarsType type in my application code

marcschroeder commented 4 months ago

Hey @detomarco, this should already be possible. Try the following example:

openapi: 3.0.1
info:
  title: example
  version: 0.0.1
paths:
  /cars:
    get:
      operationId: me
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/Cars'
          description: OK
components:
  schemas:
    Cars:
      type: object
      properties:
        types:
          type: string
          $ref: '#/components/schemas/CarType'
    CarType:
      type: string
      enum:
        - FERRARI
        - FORD
        - BMW

Running the command you mentioned should generate a separate file for you that contains an actual typescript enum that you can reuse in your application.

detomarco commented 4 months ago

Thanks, that worked indeed.

I'll close this issue!!