Open
Description
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: bb81fc1)
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
- Run codegen by the above command
- Cd into output directory, then run
npm install
- 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.