Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG][typescript-fetch] Typescript error in generated code for endpoint returning type boolean #2870

Closed
5 of 6 tasks
matthewbpt opened this issue May 11, 2019 · 13 comments · Fixed by #4028
Closed
5 of 6 tasks

Comments

@matthewbpt
Copy link

matthewbpt commented May 11, 2019

Bug Report Checklist

  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator (example)?
  • What's the version of OpenAPI Generator used? 4.0.0-beta3 from npm
  • Have you search for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Bounty to sponsor the fix (example)
Description

When generating the typescript api client, the generated client has type errors for any methods returning a boolean.

export class UserApi extends runtime.BaseAPI {

    async userEmailExistsRaw(requestParameters: UserEmailExistsRequest): Promise<runtime.ApiResponse<boolean>> {
        if (requestParameters.email === null || requestParameters.email === undefined) {
            throw new runtime.RequiredError('email','Required parameter requestParameters.email was null or undefined when calling userEmailExists.');
        }

        const queryParameters: runtime.HTTPQuery = {};

        const headerParameters: runtime.HTTPHeaders = {};

        const response = await this.request({
            path: `/api/1.0/users/userExists/{email}`.replace(`{${"email"}}`, encodeURIComponent(String(requestParameters.email))),
            method: 'GET',
            headers: headerParameters,
            query: queryParameters,
        });

        return new runtime.TextApiResponse(response);
    }

    async userEmailExists(requestParameters: UserEmailExistsRequest): Promise<boolean> {
        const response = await this.userEmailExistsRaw(requestParameters);
        return await response.value();
    }
}

The return statement from userEmailExistsRaw has error:

Type 'TextApiResponse' is not assignable to type 'ApiResponse<boolean>'.
  Types of property 'value' are incompatible.
    Type '() => Promise<string>' is not assignable to type '() => Promise<boolean>'.
      Type 'Promise<string>' is not assignable to type 'Promise<boolean>'.
        Type 'string' is not assignable to type 'boolean'.ts(2322)
openapi-generator version

4.0.0-beta3 from npm

OpenAPI declaration file content or url
---
swagger: '2.0'
info:
  description: Operations related to the API
  version: '1.0'
  title: API
host: api.example.com
basePath: "/"
tags:
- name: User
  description: All apis relating to Users
schemes:
- http
- https
produces:
- application/xml
- application/json
paths:
  "/api/1.0/users/userExists/{email}":
    get:
      tags:
      - User
      operationId: userEmailExists
      parameters:
      - name: email
        in: path
        description: email
        required: true
        type: string
      responses:
        '200':
          description: Successfully retrieved result!
          schema:
            type: boolean
  "/api/1.0/users/id/{id}":
    get:
      tags:
      - User
      summary: Get specific User by id
      operationId: findUserById
      parameters:
      - name: id
        in: path
        description: id
        required: true
        type: integer
        format: int64
      responses:
        '200':
          description: Successfully retrieved result!
          schema:
            "$ref": "#/definitions/UserDto"
definitions:
  UserDto:
    type: object
    required:
    - id
    - email
    - firstName
    - lastName
    properties:
      id:
        type: integer
        format: int64
      email:
        type: string
      firstName:
        type: string
      lastName:
        type: string
    title: UserDto
Command line used for generation

openapi-generator generate --additional-properties supportsES6=true -i ./openapi.yaml -g typescript-fetch -o out/typescript-fetch

Steps to reproduce

Save yaml to openapi.yaml in current directory and run the command above.

Suggest a fix

Since true and false are both valid json responses, should the return statement simple be return new runtime.JSONApiResponse(response); (This also satisfies the typechecker)

@auto-labeler
Copy link

auto-labeler bot commented May 11, 2019

👍 Thanks for opening this issue!
🏷 I have applied any labels matching special text in your issue.

The team will review the labels and make any necessary changes.

@matthewbpt matthewbpt changed the title [BUG][typescript-fetch] Typeerror in generated code for endpoint returning type boolean [BUG][typescript-fetch] Typescript error in generated code for endpoint returning type boolean May 11, 2019
@macjohnny
Copy link
Member

@matthewbpt is this issue still present?
would you like to implement a fix for this?

@matthewbpt
Copy link
Author

Hi @macjohnny , the issue is still present as far as I can see. I was thinking of implementing a fix when I reported the issue, but did not find the time, and we decided to use the typescript-axios generator instead as it does not have this issue.

@macjohnny
Copy link
Member

cc @TiFu

@TiFu
Copy link
Contributor

TiFu commented Jul 24, 2019

I think the issue is probably in this line:

https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache#L214

The fix could be as simple as adding additional conditions here and adding a new response type to https://github.com/OpenAPITools/openapi-generator/blob/master/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache

Unfortunately I don't have time to implement this as I will be moving to another country next week.

@macjohnny
Copy link
Member

@matthewbpt would you give us a hand and try to fix it with @TiFu's suggestion?

@ffMathy
Copy link
Contributor

ffMathy commented Oct 2, 2019

This is still present today on the latest version.

@ffMathy
Copy link
Contributor

ffMathy commented Oct 2, 2019

The ironic part is that if you look at userEmailExistsRaw, it actually contains the correct return type, but isn't able to write out the correct return statement.

Should be relatively simple to fix, but I don't have much time.

@pavel-zdenek
Copy link

We have fixed this for our project by dropping primitive return values altogether in favour of objects with a single value of the primitive type. It can even be considered "better design" (i.e. consistent JSON) but not applicable for every one and every project out there.

ffMathy added a commit to ffMathy/openapi-generator that referenced this issue Oct 2, 2019
macjohnny pushed a commit that referenced this issue Oct 2, 2019
* Update apis.mustache

Fixes #3709 and #2870.

* Update apis.mustache

* added new petstore code.
Jesse0Michael pushed a commit to Jesse0Michael/openapi-generator that referenced this issue Oct 3, 2019
* Update apis.mustache

Fixes OpenAPITools#3709 and OpenAPITools#2870.

* Update apis.mustache

* added new petstore code.
matthewbpt added a commit to matthewbpt/openapi-generator that referenced this issue Oct 5, 2019
@keesvanlierop
Copy link

Typings are fixed, but serialization of the responses is still incorrect with runtime.TextApiResponse instead of runtime.JSONApiResponse. @matthewbpt were you able to fix it with the latest commits you've pushed in your fork? If so, can you submit a PR?

@pengcheng
Copy link

I think the root cause is the CodeGen uses return data type while choosing TextApiResponse or JSONApiResponse, this seems incorrect, we should use the content type (i.e. application/json) in the response body definition instead, if it is 'application/json', JSONApiResponse should be used for all types (object, simple type, etc).

@tobq
Copy link

tobq commented Oct 13, 2022

This is still an issue - 6.2.0 @pavel-zdenek

@borispetrovdev
Copy link

Confirmed still an issue in 6.2.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

10 participants