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

[typescript-axios] Add option to add NodeJS imports #10990

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions bin/configs/typescript-axios-with-node-imports.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
generatorName: typescript-axios
outputDir: samples/client/petstore/typescript-axios/builds/with-node-imports
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-operations-without-required-params.yaml
templateDir: modules/openapi-generator/src/main/resources/typescript-axios
additionalProperties:
withNodeImports: "true"
multipartFormData: "true"
1 change: 1 addition & 0 deletions docs/generators/typescript-axios.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|supportsES6|Generate code that conforms to ES6.| |false|
|useSingleRequestParameter|Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.| |false|
|withInterfaces|Setting this property to true will generate interfaces next to the default class implementations.| |false|
|withNodeImports|Setting this property to true adds imports for NodeJS| |false|
|withSeparateModelsAndApi|Put the model and api in separate folders and in separate classes| |false|
|withoutPrefixEnums|Don't prefix enum names with class names| |false|

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public class TypeScriptAxiosClientCodegen extends AbstractTypeScriptClientCodege
public static final String SEPARATE_MODELS_AND_API = "withSeparateModelsAndApi";
public static final String WITHOUT_PREFIX_ENUMS = "withoutPrefixEnums";
public static final String USE_SINGLE_REQUEST_PARAMETER = "useSingleRequestParameter";
public static final String WITH_NODE_IMPORTS = "withNodeImports";

protected String npmRepository = null;

Expand All @@ -55,6 +56,7 @@ public TypeScriptAxiosClientCodegen() {
this.cliOptions.add(new CliOption(SEPARATE_MODELS_AND_API, "Put the model and api in separate folders and in separate classes", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(WITHOUT_PREFIX_ENUMS, "Don't prefix enum names with class names", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(USE_SINGLE_REQUEST_PARAMETER, "Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
this.cliOptions.add(new CliOption(WITH_NODE_IMPORTS, "Setting this property to true adds imports for NodeJS", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
// Templates have no mapping between formatted property names and original base names so use only "original" and remove this option
removeOption(CodegenConstants.MODEL_PROPERTY_NAMING);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@
{{^withSeparateModelsAndApi}}
import { Configuration } from './configuration';
import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios';
{{#withNodeImports}}
// URLSearchParams not necessarily used
// @ts-ignore
import { URL, URLSearchParams } from 'url';
{{#multipartFormData}}
import FormData from 'form-data'
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if this should have // @ts-ignore – it is of course possible to set the multipartFormData parameter for a spec that does not have any form data endpoints and then this import would be unused (and probably the form-data dependency is missing too if not needed), but then again is it a user error if they configure to use something that is not needed?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is it a user error if they configure to use something that is not needed?

In my view, it totally is. Or otherwise put - if you declared your need for this code but it's not there (e.g. you want to manually extend the file), would that not be a generation error?


In my humble opinion, neither of eslint-disable, tslint:disable or ts-ignore should be present in this file. All of the unused imports can and should be fixed using eslint --fix, prettier --write or whatever code formatter someone uses. Since this is a programatic change, not a manual one, you can consistently apply it after each generation.

That's how I do it. I remove all these comments using sed after generating the source code and before formatting. The only warnings I get are related to the use of any typings.

Besides, tslint has also been deprecated since 2019.

Btw, typescript-node has quite a few linting errors, including circular dependencies - yet another reason to deprecate that generator template.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

eslint --fix doesn't fix unused imports
and TS itself doesn't have autofix capability (so noUnusedLocals compiler setting will simply fail to compile the generated code)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@amakhrov I'm using eslint-plugin-unused-imports to remove unused imports.

IMO, the generated code should either be valid, or not disable linting. The latter is especially tricky, since you must support all linting tooling (e.g. there should also be a .prettierignore), which to me seems unfeasable.

What other code generators do, is lint and/or format the code themselves after generation. That could be an option for JS as well.

But we are diverging from the topic of the PR.

{{/multipartFormData}}
{{/withNodeImports}}
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@

import globalAxios, { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios';
import { Configuration } from '{{apiRelativeToRoot}}configuration';
{{#withNodeImports}}
// URLSearchParams not necessarily used
// @ts-ignore
import { URL, URLSearchParams } from 'url';
{{#multipartFormData}}
import FormData from 'form-data'
{{/multipartFormData}}
{{/withNodeImports}}
// Some imports not used depending on template conditions
// @ts-ignore
import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '{{apiRelativeToRoot}}common';
Expand Down Expand Up @@ -184,7 +192,7 @@ export const {{classname}}AxiosParamCreator = function (configuration?: Configur
{{/bodyParam}}
setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers};
localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions,{{#hasFormParams}}{{#multipartFormData}} ...(localVarFormParams as any).getHeaders?.(),{{/multipartFormData}}{{/hasFormParams}} ...options.headers};
{{#hasFormParams}}
localVarRequestOptions.data = localVarFormParams{{#vendorExtensions}}{{^multipartFormData}}.toString(){{/multipartFormData}}{{/vendorExtensions}};
{{/hasFormParams}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
import { Configuration } from "./configuration";
import { RequiredError, RequestArgs } from "./base";
import { AxiosInstance, AxiosResponse } from 'axios';
{{#withNodeImports}}
import { URL, URLSearchParams } from 'url';
{{/withNodeImports}}

/**
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
wwwroot/*.js
node_modules
typings
dist
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# empty npmignore to ensure all required files (e.g., in the dist folder) are published by npm
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator

# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.

# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs

# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux

# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux

# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.gitignore
.npmignore
api.ts
base.ts
common.ts
configuration.ts
git_push.sh
index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
5.3.1-SNAPSHOT
Loading