openapi-generator icon indicating copy to clipboard operation
openapi-generator copied to clipboard

[BUG] [TypeScript-Fetch] Incorrectly generated models when using oneOf

Open frederikprijck opened this issue 3 years ago • 20 comments

Bug Report Checklist

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

When using oneOf with the TypeScript-Fetch generator, the models are generated incorrectly in two ways:

  • It generates references to functions that do not exist
  • It incorrectly handles generics

An example repository can be found at https://github.com/frederikprijck/openapi-typescript-fetch-one-of, which includes a minimal spec file, as well as the generated code.

The generated output can be seen on the reproduction repository on GitHub, but here are the relevant bits:

export function TestUrlFromJSONTyped(json: any, ignoreDiscriminator: boolean): TestUrl {
    if ((json === undefined) || (json === null)) {
        return json;
    }
    return { ...Array<string>FromJSONTyped(json, true), ...stringFromJSONTyped(json, true) };
}

export function TestUrlToJSON(value?: TestUrl | null): any {
    if (value === undefined) {
        return undefined;
    }
    if (value === null) {
        return null;
    }

    if (instanceOfArray<string>(value)) {
        return Array<string>ToJSON(value as Array<string>);
    }
    if (instanceOfstring(value)) {
        return stringToJSON(value as string);
    }

    return {};
}

As you can see:

  • stringFromJSONTyped, instanceOfArray and stringToJSON do not exist
  • Array<string>FromJSONTyped, instanceOfArray<string> and Array<string>ToJSON do not exist but are also not valid.

The first issue appears with different types as well, such as number. While the second is a bit of a different issue and not sure it requires a different issue report. Happy to do so if needed.

openapi-generator version

@openapitools/openapi-generator-cli version 2.5.2 on NPM with 6.3.0 in the OpenAPITools.json.

OpenAPI declaration file content or url

The entire (minimal) file is available at the reproduction repository on GitHub, but here are the relevant bits:

"components": {
  "schemas": {
    "test": {
      "type": "object",
      "properties": {
        "url": {
          "description": "Test Url(s).",
          "oneOf": [
            { "type": "array", "items": { "type": "string" } },
            { "type": "string" }
          ]
        }
      }
    }
  }
},
Generation Details

You can run npm run generate after cloning the sample repository, or use:

openapi-generator-cli generate -i ./api.json -o src/generated -g typescript-fetch
Steps to reproduce
  • git clone [email protected]:frederikprijck/openapi-typescript-fetch-one-of.git
  • cd openapi-typescript-fetch-one-of
  • npm i
  • npm run generate
  • cat src/generated/models/TestUrl.ts

Or using Docker:

docker run --rm -v "${PWD}:/local" openapitools/openapi-generator-cli generate \
    -i https://raw.githubusercontent.com/frederikprijck/openapi-typescript-fetch-one-of/main/api.json \
    -g typescript-fetch \
    -o /local/out/typescript-fetch

Followed by cat out/typescript-fetch/models/TestUrl.ts

Related issues/PRs

There are a lot of issues regarding oneOf and TypeScript, but couldn't really find much that felt related apart from this one:

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

This looks as if it's exactly the same issue as the first of the issues (so not the generic Array one), but for query parameters instead of schema properties. I also noticed that the issue is closed, has a merged PR linked but I am still seeing the exact same output on the latest master, see my comment on the issue.

Suggest a fix

I don't think I have any idea. I would be happy to help fix this, but will need some pointers.

frederikprijck avatar Feb 20 '23 13:02 frederikprijck

I can confirm, we have the same issue with v6.4.0 (since v6.1.0), for polymorphic models it is even worse, as it tries to use instanceOf<ChildModel>. With version v6.0.0 everything is working for us.

We use the following options: --additional-properties=withInterfaces=true,stringEnums=true

Linus-Boehm avatar Feb 23 '23 12:02 Linus-Boehm

Thanks for chiming in @Linus-Boehm, to avoid confusion, I want to mention that the issue being reported here is not entirly fixed when pinning to 6.0.0.

The instanceOf part of the issue is, but the FromJSON / ToJSON are not.

Nevertheless, that's good information to know.

frederikprijck avatar Feb 23 '23 12:02 frederikprijck

I think some related issues are:

  • #14806
  • #14611
  • #14801

jackkinsella avatar Feb 24 '23 20:02 jackkinsella

Thanks @jackkinsella.

There's definetly one (ts-fetch) related to the instanceof issue, but not the FromJson/ToJson. Regardless, Great to get these connected! Thanks

The other two seems to be unrelated, one is even about golang, which is an entirly different generator. The other is about incorrect import path.

Just mentioning to avoid confusion.

frederikprijck avatar Feb 25 '23 11:02 frederikprijck

I had both instanceOf and spread types errors and rolling back to 5.4.0 resolved both of them. Obviously, it's not ideal, but if you roll back to 5.4.0 does it solve both issues for you?

eliw00d avatar Jun 01 '23 15:06 eliw00d

Are there any updates with this?

balloman avatar Dec 13 '23 20:12 balloman

Any updates here?

devgertschi avatar Jan 22 '24 10:01 devgertschi

Getting the same issue. Any updates?

renzoafable avatar Jan 25 '24 12:01 renzoafable

I am also running into this - any updates?

austinhulak avatar Feb 19 '24 22:02 austinhulak

Running into the same issue, any updates or plans to address this?

pelhage avatar Mar 07 '24 22:03 pelhage

We ended up adding a post processing layer using handlebars to parse for problematic output and convert it into correct output.

On Thu, Mar 7, 2024 at 10:36 PM Patrick El-Hage @.***> wrote:

Running into the same issue, any updates or plans to address this?

— Reply to this email directly, view it on GitHub https://github.com/OpenAPITools/openapi-generator/issues/14763#issuecomment-1984670074, or unsubscribe https://github.com/notifications/unsubscribe-auth/AABE5JX6IGQI7P2XQVZOBCLYXDTWZAVCNFSM6AAAAAAVB4CO7SVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTSOBUGY3TAMBXGQ . You are receiving this because you were mentioned.Message ID: @.***>

jackkinsella avatar Mar 08 '24 17:03 jackkinsella

Any news???

6feferonka9 avatar Mar 11 '24 18:03 6feferonka9

hey any news on this?

denisvanmorgan avatar Mar 11 '24 18:03 denisvanmorgan

Same issue here. Any updates?

anthonytamez avatar Mar 12 '24 21:03 anthonytamez

@frederikprijck I think I've created a fix for a similar issue: https://github.com/OpenAPITools/openapi-generator/pull/18154

Can you check if this fixes your issue? It solved mine.

giovannicimolin avatar Mar 18 '24 20:03 giovannicimolin

Two temporary solutions:

  1. Add mapping to opanapi spec. Example:
			"SomeType": {
				"oneOf": [ {
					"$ref": "#/components/schemas/Blah1"
				}, {
					"$ref": "#/components/schemas/Blah2"
				} ],
				"type": "object",
				"properties": {
					"objectType": {
						"type": "string"
					}
				},
				"required": [ "objectType" ],
				"discriminator": {
					"propertyName": "objectType",
					//add this, which is the same as oneOf above:
					"mapping": {
						"Blah1": "#/components/schemas/Blah1",
						"Blah2": "#/components/schemas/Blah2"
					}
				}
			},
  1. use typescript-axios generator, it generates everything without problems: npx @openapitools/openapi-generator-cli generate -i ./openapi.json -g typescript-axios -o packages/openapi/out -c ./openapiconfig.json --global-property models,supportingFiles

welschmoor avatar Jul 09 '24 13:07 welschmoor

Same issue on 7.7.0.

My solution is to add ts-nocheck to files with oneOf:

diff --git a/src/api/models/JobPostArgs.ts b/src/api/models/JobPostArgs.ts
--- a/src/api/models/JobPostArgs.ts
+++ b/src/api/models/JobPostArgs.ts
@@ -1,3 +1,4 @@
+// @ts-nocheck
 /* tslint:disable */
 /* eslint-disable */
 /**
patch -p1 < ./api-hotfix.patch

SL-RU avatar Aug 08 '24 19:08 SL-RU

Looks like this PR could be a fix: https://github.com/OpenAPITools/openapi-generator/pull/18740

ghost avatar Jan 14 '25 17:01 ghost

Seeing this problem now, our case is a property in a DTO via Nestjs which can be string | number | boolean | string[]. None of the workarounds I have found either in this repo or Nestjs forums have worked. #18740 mirrors our case but seems to be kind of dead. Sadly I don't have time or competence to contribute.

Here's what our implementation looks like:

Nestjs
export class FilterConditionDto {
  @ApiProperty({ enum: FilterOperator })
  @IsEnum(FilterOperator)
  operator: FilterOperator;

  @ApiProperty({
    oneOf: [
      { type: "string" },
      { type: "number" },
      { type: "boolean" },
      { type: "array", items: { type: "string" } },
    ],
  })
  value: string | number | boolean | string[];
}
Generated Swagger
{
  "FilterConditionDto": {
    "type": "object",
    "properties": {
      "operator": {
        "type": "string",
        "enum": [
          "eq",
          "neq",
          "gt",
          "lt",
          "gte",
          "lte",
          "like",
          "ilike",
          "in",
          "nin",
          "isnull",
          "notnull"
        ]
      },
      "value": {
        "oneOf": [
          {
            "type": "string"
          },
          {
            "type": "number"
          },
          {
            "type": "boolean"
          },
          {
            "type": "array",
            "items": {
              "type": "string"
            }
          }
        ]
      }
    },
    "required": ["operator", "value"]
  }
}
Resulting generated `typescript-fetch` code
// [...]
export function FilterConditionDtoValueFromJSONTyped(json: any, ignoreDiscriminator: boolean): FilterConditionDtoValue {
    if (json == null) {
        return json;
    }
    if (instanceOfArray<string>(json)) { // Cannot find name 'instanceOfArray'.
        return Array<string>FromJSONTyped(json, true); // Cannot find name 'FromJSONTyped'.
    }
    if (instanceOfboolean(json)) { // Cannot find name 'instanceOfboolean'.
        return booleanFromJSONTyped(json, true); // Cannot find name 'booleanFromJSONTyped'.
    }
    if (instanceOfnumber(json)) { // Cannot find name 'instanceOfnumber'.
        return numberFromJSONTyped(json, true); // Cannot find name 'numberFromJSONTyped'.
    }
    if (instanceOfstring(json)) { // Cannot find name 'instanceOfstring'.
        return stringFromJSONTyped(json, true); // Cannot find name 'stringFromJSONTyped'.
    }

    return {} as any;
}
// [...]

fullyherge avatar Apr 16 '25 10:04 fullyherge

I generally try to avoid oneOf when writing new OpenAPI specs, as it doesn't usually play nicely with any generators in my experience. But I wanted to generate a client for an API that I can't change that makes some use of oneOf.

A non-ideal workaround that let me move on with my day was replacing the oneOf with just a description. This generates that property as someProperty?: object;.

For any non primitives, I make sure to reference its specification elsewhere so the model at least gets generated.

I then document the oneOf elsewhere, and do the type checks manually on the client.

This way I can still have most of the code be auto generated. Just have to live with these exceptional cases being hard to use.

I know this isn't a real solution, but hope it helps someone.

joaocanaverde-blue avatar May 06 '25 13:05 joaocanaverde-blue