Skip to content

[Javascript] special handling of 204 response needed #4554

@tharders

Description

@tharders
Description

The generated ApiClient.js treats a 204 response with no data as a normal 200 response, where data is expected.

When a request retuns a status 204 with no data in the body, the superagent library will treat this as a success and return an empty object.
The api client will call convertToType with the empty object, which will result in unexpected data.

For array responses this will even result in an error.
When the type parameter is an array convertToType assumes that data is also an array, which it is not.
That will cause the error "data.map is not a function"

Swagger-codegen version

Using http://editor.swagger.io

Swagger declaration file content or url
swagger: '2.0'
info:
  version: "0.0.1"
  title: Test API
produces:
  - application/json
paths:
  /test:
   get:
      responses:
        200:
          description: Success
          schema:
            type: array
            description: array of results
            items:
              type: string
Command line used for generation

http://editor.swagger.io

Steps to reproduce

Generate a javascript client with the example code and let the server return 204 without any body.
Then calling the api should reproduce the problem.

Related issues

I saw that the 204 was an issue with other languages.
Maybe it should be testest with the all languages if the 204 is handled correctly.

Suggest a Fix

I fixed this by checking for status 204 in the deserialize method of the ApiClient.js and returning null in this case.

    exports.prototype.deserialize = function deserialize(response, returnType) {
        if (response == null || returnType == null) {
            return null;
        }
        if (response.status == 204) {
            return null;
        }

I also added a try catch around the call to deserialize to avoid unhandled exceptions like the "data.map is not a function"

                if (!error) {
                    try {
                        data = _this.deserialize(response, returnType);
                    } catch (err) {
                        error = err;
                    }
                }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions