OpenAPITools / OpenAPITools/openapi-generator

[BUG][typescript-fetch] "allOf" generates invalid api model name

Open
#10,950 0 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Issue: Bug
Dominant language
Java
Stars
26.8k
Forks
7.7k
PR merge metrics
PR metrics pending

Description

Bug Report Checklist
  • Have you provided a full/minimal spec to reproduce the issue?
  • Have you validated the input using an OpenAPI validator (example)?
  • Have you tested with the latest master to confirm the issue still exists?
  • Have you searched for related issues/PRs?
  • What's the actual output vs expected output?
  • [Optional] Sponsorship to speed up the bug fix or feature request (example)
Description

I have experienced this issue, and dived a bit into the generator code, and will try to line out based on the actual generator what I think the underlying issue is. But first let me describe the observed behaviour:

Given a valid openApi spec with an endpoint response using allOf described as such:

      responses:
        '200':
          Returns entity if entity can be returned
          content:
            application/json:
              schema:
                allOf:
                  - $ref: '#/components/schemas/Result'
                  - $ref: '#/components/schemas/Entity'

Will generate typescript code such as:


    async postEntityRaw(requestParameters: PostPlayerDepositAddressRequest): Promise<runtime.ApiResponse<Result & Entity>> {
        if (requestParameters.id === null || requestParameters.id === undefined) {
            throw new runtime.RequiredError('id','Required parameter requestParameters.id was null or undefined when calling postEntity.');
        }

        const queryParameters: any = {};

        const headerParameters: runtime.HTTPHeaders = {};

        const response = await this.request({
            path: `/entities/{id}`.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters.id))),
            method: 'POST',
            headers: headerParameters,
            query: queryParameters,
        });

        return new runtime.JSONApiResponse(response, (jsonValue) => Result &amp; EntityFromJSON(jsonValue));
    }

The issue here is in the (jsonValue) => Result &amp; EntityFromJSON(jsonValue) arrow function. Obviously Result &amp; EntityFromJSON(jsonValue) is invalid syntax.

But this seems to be totally by design:

The name (X & Y) is created as such here: https://github.com/OpenAPITools/openapi-generator/blob/4d947a1c4579a73c7350ea55153d33ef76ba5d89/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java#L934

And then the typename is used to create the call to the model's function here: https://github.com/OpenAPITools/openapi-generator/blob/ff13923f55ebe840d20252830abd9f8ff5fdb1ef/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache#L314

Suggest a fix

The issue here is, while the generated type is a correct typescript type (Result & Entity) there is no such model generated.

I think there are 2 ways to solve this:

Create a concrete model for each allOf type (e.g. ResultEntity) which also implements the fromJson function. (Additional overhead and duplicated json serializer code)

Or leverage the existing models to marshal the JSON into 2 javascript objects and then merge those 2 javascript objects:

So the resulting code could look somthing like

 (jsonValue) => Object.assign({}, ResultFromJson(jsonValue), EntityFromJSON(jsonValue))

Although I would not know how to update the template to get the underlying typenames. And this would need to work for an arbitrary amount of models/types/allOf argument not just 2. If someone could point me otosome documentation on how to work with these templates I could give it a shot to fix this myself.

openapi-generator version

5.2.0 but that seems by design still in the current version

Related issues/PRs

https://github.com/OpenAPITools/openapi-generator/issues/3281

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with AbstractTypeScriptClientCodegen.java at the linked allOf type-name construction and typescript-fetch/apis.mustache at the linked response deserialization call. Reproduce the shown allOf case and determine how generated code should deserialize every referenced type; done means the generated TypeScript is valid and correctly handles arbitrary allOf members.

Written by the indexing model from the issue text.

Assessment

Tech stack
java, openapi, typescript
Domain
api, tooling
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.