swagger-api/swagger-codegen

Javascript client produces a wrong object for a string enum type that is used with $ref

Open

#4,819 opened on 2017年2月17日

GitHub で見る
 (39 comments) (0 reactions) (0 assignees)HTML (12,701 stars) (5,474 forks)batch import
Client: JavaScript/Node.jsFeature: EnumIssue: Bughelp wanted

説明

Description

I got something like { '0': 'f', '1': 'i', '2': 's', '3': 'h' } for an enum type. It should be "fish".

Swagger-codegen version

2.2.2-SNAPSHOT (revision: bb81fc130aedd64a4d35232d5173b12ce758e967)

Swagger declaration file content or url
swagger: "2.0"
info:
  version: 1.0.0
schemes:
  - http
paths:
  /pet:
    post:
      parameters:
      responses:
        '405':
          description: Invalid input

definitions:
  EnumArrays:
    type: object
    properties:
      array_enum:
        type: array
        items:
          type: string
          enum:
            - fish
            - crab
      array_enum_ref:
        type: array
        items:
          $ref: '#/definitions/StringEnumObject'
  StringEnumObject:
    type: string
    enum:
      - fish
      - crab
Command line used for generation
$ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate -i test.yaml -l javascript -o output
Steps to reproduce
  1. Run codegen by the above command
  2. Cd into output directory, then run npm install
  3. Start a node interactive shell and type them:
$ node
> var SwaggerClient = require('./src')
> SwaggerClient.EnumArrays.constructFromObject({"array_enum": ["fish", "crab"]})
exports { array_enum: [ 'fish', 'crab' ] }
> SwaggerClient.EnumArrays.constructFromObject({"array_enum_ref": ["fish", "crab"]})
exports {
  array_enum_ref: 
   [ { '0': 'f', '1': 'i', '2': 's', '3': 'h' },
     { '0': 'c', '1': 'r', '2': 'a', '3': 'b' } ] }
Related issues

I did not find any known issues about it. However, there were a number of bugs related to enum types with Javascript client in the past.

#3639 [javascript client] constructFromObject calls undefined function constructFromObject on enums #3416 [JavaScript] String Enum types produce invalid code #2102 [JavaScript] Enums are not exported correctly

Suggest a Fix

I can fix the issue by modifying convertToType method defined in ApiClient.mustache like this:

--- a/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache
+++ b/modules/swagger-codegen/src/main/resources/Javascript/ApiClient.mustache
@@ -470,7 +470,7 @@
         if (type === Object) {
           // generic object, return directly
           return data;
-        } else if (typeof type === 'function') {
+        } else if (typeof type.constructFromObject === 'function') {
           // for model type like: User
           return type.constructFromObject(data);
         } else if (Array.isArray(type)) {

I think ApiClient.convertToType() can always call type.constructFromObject() for types that have constructFromObject method. But I'm not sure about its side effects.

コントリビューターガイド