[typescript-rxjs] performance improvements, bugfix for falsy parameters (#4250)

* perf(typescript-rxjs): remove redundant check when building auth header

* feat(typescript-rxjs): destructure request parameters, add throwIfNullOrUndefined helper, build query object more efficently

* fix(typescript-rxjs): change form checks back from null to undefined

* feat(typescript-rxjs): regenerate samples

* feat(typescript-rxjs): add hasRequiredQueryParams flag for improved query object generation

* feat(typescript-rxjs): remove trailing comma in param destructuring, improve formatting via hasOptionalQueryParams flag

* feat(typescript-rxjs): remove useless generics in BaseAPI

* feat(typescript-rxjs): regenerate samples

* feat(typescript-rxjs): extend CodegenParameter by output.paramNameAlternative and output.paramNameOrAlternative

* refactor(typescript-rxjs): remove obsolete reservedWords RequiredError and exists

* feat(typescript-rxjs): add reservedParamNames list with headers, query and formData, extend param processing

* feat(typescript-rxjs): use paramNameOrAlternative in api template

* refactor(typescript-rxjs): replace paramNameOrAlternative prop with mustache partial

* refactor(typescript-rxjs): reduce branching in configuration's apiKey() and accessToken()

* refactor(typescript-rxjs): remove unused ModelPropertyNaming

* feat(typescript-rxjs): regenerate samples

* feat(typescript-rxjs): remove CodegenParamter's paramNameAlternative, use vendorExtensions instead

* docs(typescript-rxjs): regenerate readme
This commit is contained in:
Bernd Hacker
2020-01-27 09:31:36 +01:00
committed by Esteban Gehring
parent 4f350bc01c
commit 45f26fe0bd
21 changed files with 661 additions and 587 deletions

View File

@@ -23,19 +23,20 @@ import io.swagger.v3.parser.util.SchemaTypeUtil;
import org.openapitools.codegen.*;
import org.openapitools.codegen.meta.features.DocumentationFeature;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.TreeSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.*;
public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractTypeScriptClientCodegen.class);
public static final String NPM_REPOSITORY = "npmRepository";
public static final String WITH_INTERFACES = "withInterfaces";
protected String npmRepository = null;
protected Set<String> reservedParamNames = new HashSet<>();
public TypeScriptRxjsClientCodegen() {
super();
@@ -58,6 +59,11 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
this.cliOptions.add(new CliOption(NPM_REPOSITORY, "Use this property to set an url your private npmRepo in the package.json"));
this.cliOptions.add(new CliOption(WITH_INTERFACES, "Setting this property to true will generate interfaces next to the default class implementations.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString()));
// these are used in the api template for more efficient destructuring
this.reservedParamNames.add("headers");
this.reservedParamNames.add("query");
this.reservedParamNames.add("formData");
}
@Override
@@ -252,12 +258,18 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
operations.put("hasEnums", hasEnums);
}
private void setParamNameAlternative(CodegenParameter param, String paramName, String paramNameAlternative) {
if (param.paramName.equals(paramName)) {
param.vendorExtensions.put("paramNameAlternative", paramNameAlternative);
}
}
private void addConditionalImportInformation(Map<String, Object> operations) {
// This method will determine if there are required parameters and if there are list containers
Map<String, Object> _operations = (Map<String, Object>) operations.get("operations");
List<ExtendedCodegenOperation> operationList = (List<ExtendedCodegenOperation>) _operations.get("operation");
boolean hasRequiredParameters = false;
boolean hasRequiredParams = false;
boolean hasListContainers = false;
boolean hasHttpHeaders = false;
boolean hasQueryParams = false;
@@ -265,25 +277,46 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
for (ExtendedCodegenOperation op : operationList) {
if (op.getHasRequiredParams()) {
hasRequiredParameters = true;
hasRequiredParams = true;
}
for (CodegenParameter param : op.headerParams) {
if (param.isListContainer) {
hasListContainers = true;
break;
for (CodegenParameter p: op.allParams) {
String paramNameAlternative = null;
if(this.reservedParamNames.contains(p.paramName)){
paramNameAlternative = p.paramName + "Alias";
LOGGER.info("param: "+p.paramName+" isReserved > "+paramNameAlternative);
}
}
for (CodegenParameter param : op.queryParams) {
if (param.isListContainer && !param.isCollectionFormatMulti) {
hasListContainers = true;
break;
setParamNameAlternative(p, p.paramName, paramNameAlternative);
for (CodegenParameter param : op.headerParams) {
if (param.isListContainer) {
hasListContainers = true;
}
setParamNameAlternative(param, p.paramName, paramNameAlternative);
}
}
for (CodegenParameter param : op.formParams) {
if (param.isListContainer && !param.isCollectionFormatMulti) {
hasListContainers = true;
break;
for (CodegenParameter param : op.queryParams) {
if (param.isListContainer && !param.isCollectionFormatMulti) {
hasListContainers = true;
}
if (param.required) {
op.hasRequiredQueryParams = true;
} else {
op.hasOptionalQueryParams = true;
}
setParamNameAlternative(param, p.paramName, paramNameAlternative);
}
for (CodegenParameter param : op.formParams) {
if (param.isListContainer && !param.isCollectionFormatMulti) {
hasListContainers = true;
}
setParamNameAlternative(param, p.paramName, paramNameAlternative);
}
for (CodegenParameter param : op.pathParams) {
setParamNameAlternative(param, p.paramName, paramNameAlternative);
}
}
@@ -296,13 +329,9 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
if (op.getHasPathParams()) {
hasPathParams = true;
}
if(hasRequiredParameters && hasListContainers && hasHttpHeaders && hasQueryParams && hasPathParams){
break;
}
}
operations.put("hasRequiredParameters", hasRequiredParameters);
operations.put("hasRequiredParams", hasRequiredParams);
operations.put("hasListContainers", hasListContainers);
operations.put("hasHttpHeaders", hasHttpHeaders);
operations.put("hasQueryParams", hasQueryParams);
@@ -312,7 +341,6 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
private void addExtraReservedWords() {
this.reservedWords.add("BASE_PATH");
this.reservedWords.add("BaseAPI");
this.reservedWords.add("RequiredError");
this.reservedWords.add("COLLECTION_FORMATS");
this.reservedWords.add("ConfigurationParameters");
this.reservedWords.add("Configuration");
@@ -320,11 +348,9 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
this.reservedWords.add("HttpHeaders");
this.reservedWords.add("HttpQuery");
this.reservedWords.add("HttpBody");
this.reservedWords.add("ModelPropertyNaming");
this.reservedWords.add("RequestArgs");
this.reservedWords.add("RequestOpts");
this.reservedWords.add("ResponseArgs");
this.reservedWords.add("exists");
this.reservedWords.add("Middleware");
this.reservedWords.add("AjaxRequest");
this.reservedWords.add("AjaxResponse");
@@ -332,6 +358,8 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
class ExtendedCodegenOperation extends CodegenOperation {
public boolean hasHttpHeaders;
public boolean hasRequiredQueryParams;
public boolean hasOptionalQueryParams;
public ExtendedCodegenOperation(CodegenOperation o) {
super();
@@ -405,6 +433,8 @@ public class TypeScriptRxjsClientCodegen extends AbstractTypeScriptClientCodegen
// new fields
this.hasHttpHeaders = o.getHasHeaderParams() || o.getHasBodyParam() || o.hasAuthMethods;
this.hasRequiredQueryParams = false; // will be updated within addConditionalImportInformation
this.hasOptionalQueryParams = false; // will be updated within addConditionalImportInformation
}
}
}

View File

@@ -1,7 +1,7 @@
// tslint:disable
{{>licenseInfo}}
import { Observable } from 'rxjs';
import { BaseAPI{{#hasHttpHeaders}}, HttpHeaders{{/hasHttpHeaders}}{{#hasQueryParams}}, HttpQuery{{/hasQueryParams}}{{#hasRequiredParameters}}, throwIfRequired{{/hasRequiredParameters}}{{#hasPathParams}}, encodeURI{{/hasPathParams}}{{#hasListContainers}}, COLLECTION_FORMATS{{/hasListContainers}} } from '../runtime';
import { BaseAPI{{#hasHttpHeaders}}, HttpHeaders{{/hasHttpHeaders}}{{#hasQueryParams}}, HttpQuery{{/hasQueryParams}}{{#hasRequiredParams}}, throwIfNullOrUndefined{{/hasRequiredParams}}{{#hasPathParams}}, encodeURI{{/hasPathParams}}{{#hasListContainers}}, COLLECTION_FORMATS{{/hasListContainers}} } from '../runtime';
{{#imports.0}}
import {
{{#imports}}
@@ -37,11 +37,11 @@ export class {{classname}} extends BaseAPI {
* {{&summary}}
{{/summary}}
*/
{{nickname}} = ({{#allParams.0}}requestParameters: {{operationIdCamelCase}}Request{{/allParams.0}}): Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> => {
{{nickname}} = ({{#allParams.0}}{ {{#allParams}}{{paramName}}{{#vendorExtensions.paramNameAlternative}}: {{vendorExtensions.paramNameAlternative}}{{/vendorExtensions.paramNameAlternative}}{{^-last}}, {{/-last}}{{/allParams}} }: {{operationIdCamelCase}}Request{{/allParams.0}}): Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> => {
{{#hasParams}}
{{#allParams}}
{{#required}}
throwIfRequired(requestParameters, '{{paramName}}', '{{nickname}}');
throwIfNullOrUndefined({{> paramNamePartial}}, '{{nickname}}');
{{/required}}
{{/allParams}}
@@ -58,15 +58,15 @@ export class {{classname}} extends BaseAPI {
{{/bodyParam}}
{{#headerParams}}
{{#isListContainer}}
...(requestParameters.{{paramName}} && { '{{baseName}}': requestParameters.{{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])) }),
...({{> paramNamePartial}} != null ? { '{{baseName}}': {{> paramNamePartial}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])) } : undefined),
{{/isListContainer}}
{{^isListContainer}}
...(requestParameters.{{paramName}} && { '{{baseName}}': String(requestParameters.{{paramName}}) }),
...({{> paramNamePartial}} != null ? { '{{baseName}}': String({{> paramNamePartial}}) } : undefined),
{{/isListContainer}}
{{/headerParams}}
{{#authMethods}}
{{#isBasic}}
...(this.configuration.username && this.configuration.password && { Authorization: `Basic ${btoa(this.configuration.username + ':' + this.configuration.password)}` }),
...(this.configuration.username != null && this.configuration.password != null ? { Authorization: `Basic ${btoa(this.configuration.username + ':' + this.configuration.password)}` } : undefined),
{{/isBasic}}
{{#isApiKey}}
{{#isKeyInHeader}}
@@ -75,77 +75,109 @@ export class {{classname}} extends BaseAPI {
{{/isApiKey}}
{{#isOAuth}}
// oauth required
...(this.configuration.accessToken && {
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function'
...(this.configuration.accessToken != null
? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('{{name}}', [{{#scopes}}'{{{scope}}}'{{^-last}}, {{/-last}}{{/scopes}}])
: this.configuration.accessToken)
}),
: this.configuration.accessToken }
: undefined
),
{{/isOAuth}}
{{/authMethods}}
};
{{/hasHttpHeaders}}
{{#hasQueryParams}}
const query: HttpQuery = {
{{^hasRequiredQueryParams}}
const query: HttpQuery = {};
{{/hasRequiredQueryParams}}
{{#hasRequiredQueryParams}}
const query: HttpQuery = { // required parameters are used directly since they are already checked by throwIfNullOrUndefined
{{#queryParams}}
{{#required}}
{{#isListContainer}}
{{#isCollectionFormatMulti}}
...(requestParameters.{{paramName}} && { '{{baseName}}': requestParameters.{{paramName}} }),
'{{baseName}}': {{> paramNamePartial}},
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
...(requestParameters.{{paramName}} && { '{{baseName}}': requestParameters.{{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}']) }),
'{{baseName}}': {{> paramNamePartial}}.join(COLLECTION_FORMATS['{{collectionFormat}}']),
{{/isCollectionFormatMulti}}
{{/isListContainer}}
{{^isListContainer}}
{{#isDateTime}}
...(requestParameters.{{paramName}} && { '{{baseName}}': (requestParameters.{{paramName}} as any).toISOString() }),
'{{baseName}}': ({{> paramNamePartial}} as any).toISOString(),
{{/isDateTime}}
{{^isDateTime}}
{{#isDate}}
...(requestParameters.{{paramName}} && { '{{baseName}}': (requestParameters.{{paramName}} as any).toISOString() }),
'{{baseName}}': ({{> paramNamePartial}} as any).toISOString(),
{{/isDate}}
{{^isDate}}
...(requestParameters.{{paramName}} && { '{{baseName}}': requestParameters.{{paramName}} }),
'{{baseName}}': {{> paramNamePartial}},
{{/isDate}}
{{/isDateTime}}
{{/isListContainer}}
{{/required}}
{{/queryParams}}
{{#authMethods}}
{{#isApiKey}}
{{#isKeyInQuery}}
...(this.configuration.apiKey && { '{{keyParamName}}': this.configuration.apiKey && this.configuration.apiKey('{{keyParamName}}') }), // {{name}} authentication
{{/isKeyInQuery}}
{{/isApiKey}}
{{/authMethods}}
};
{{/hasRequiredQueryParams}}
{{#hasOptionalQueryParams}}
{{#queryParams}}
{{^required}}
{{#isListContainer}}
{{#isCollectionFormatMulti}}
if ({{> paramNamePartial}} != null) { query['{{baseName}}'] = {{> paramNamePartial}}; }
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
if ({{> paramNamePartial}} != null) { query['{{baseName}}'] = {{> paramNamePartial}}.join(COLLECTION_FORMATS['{{collectionFormat}}']); }
{{/isCollectionFormatMulti}}
{{/isListContainer}}
{{^isListContainer}}
{{#isDateTime}}
if ({{> paramNamePartial}} != null) { query['{{baseName}}'] = ({{> paramNamePartial}} as any).toISOString(); }
{{/isDateTime}}
{{^isDateTime}}
{{#isDate}}
if ({{> paramNamePartial}} != null) { query['{{baseName}}'] = ({{> paramNamePartial}} as any).toISOString(); }
{{/isDate}}
{{^isDate}}
if ({{> paramNamePartial}} != null) { query['{{baseName}}'] = {{> paramNamePartial}}; }
{{/isDate}}
{{/isDateTime}}
{{/isListContainer}}
{{/required}}
{{/queryParams}}
{{/hasOptionalQueryParams}}
{{#authMethods}}
{{#isApiKey}}
{{#isKeyInQuery}}
if (this.configuration.apiKey != null) { query['{{keyParamName}}'] = this.configuration.apiKey('{{keyParamName}}'); } // {{name}} authentication
{{/isKeyInQuery}}
{{/isApiKey}}
{{/authMethods}}
{{/hasQueryParams}}
{{#hasFormParams}}
const formData = new FormData();
{{/hasFormParams}}
{{#formParams}}
{{#isListContainer}}
if (requestParameters.{{paramName}}) {
if ({{> paramNamePartial}} !== undefined) {
{{#isCollectionFormatMulti}}
requestParameters.{{paramName}}.forEach((element) => {
formData.append('{{baseName}}', element as any);
})
{{> paramNamePartial}}.forEach((element) => formData.append('{{baseName}}', element as any))
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
formData.append('{{baseName}}', requestParameters.{{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}']));
formData.append('{{baseName}}', {{> paramNamePartial}}.join(COLLECTION_FORMATS['{{collectionFormat}}']));
{{/isCollectionFormatMulti}}
}
{{/isListContainer}}
{{^isListContainer}}
if (requestParameters.{{paramName}} !== undefined) {
formData.append('{{baseName}}', requestParameters.{{paramName}} as any);
}
if ({{> paramNamePartial}} !== undefined) { formData.append('{{baseName}}', {{> paramNamePartial}} as any); }
{{/isListContainer}}
{{/formParams}}
{{/hasFormParams}}
return this.request<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}>({
path: '{{{path}}}'{{#pathParams}}.replace({{=<% %>=}}'{<%baseName%>}'<%={{ }}=%>, encodeURI(requestParameters.{{paramName}})){{/pathParams}},
path: '{{{path}}}'{{#pathParams}}.replace({{=<% %>=}}'{<%baseName%>}'<%={{ }}=%>, encodeURI({{> paramNamePartial}})){{/pathParams}},
method: '{{httpMethod}}',
{{#hasHttpHeaders}}
headers,
@@ -156,14 +188,14 @@ export class {{classname}} extends BaseAPI {
{{#hasBodyParam}}
{{#bodyParam}}
{{#isContainer}}
body: requestParameters.{{paramName}},
body: {{paramName}},
{{/isContainer}}
{{^isContainer}}
{{^isPrimitiveType}}
body: requestParameters.{{paramName}},
body: {{paramName}},
{{/isPrimitiveType}}
{{#isPrimitiveType}}
body: requestParameters.{{paramName}} as any,
body: {{paramName}} as any,
{{/isPrimitiveType}}
{{/isContainer}}
{{/bodyParam}}

View File

@@ -0,0 +1,2 @@
{{! helper to output the alias of a parameter if provided and to not clutter the main template }}
{{#vendorExtensions.paramNameAlternative}}{{vendorExtensions.paramNameAlternative}}{{/vendorExtensions.paramNameAlternative}}{{^vendorExtensions.paramNameAlternative}}{{paramName}}{{/vendorExtensions.paramNameAlternative}}

View File

@@ -36,18 +36,12 @@ export class Configuration {
get apiKey(): ((name: string) => string) | undefined {
const apiKey = this.configuration.apiKey;
if (apiKey) {
return typeof apiKey === 'function' ? apiKey : () => apiKey;
}
return undefined;
return apiKey && (typeof apiKey === 'function' ? apiKey : () => apiKey);
}
get accessToken(): ((name: string, scopes?: string[]) => string) | undefined {
const accessToken = this.configuration.accessToken;
if (accessToken) {
return typeof accessToken === 'function' ? accessToken : () => accessToken;
}
return undefined;
return accessToken && (typeof accessToken === 'function' ? accessToken : () => accessToken);
}
}
@@ -61,17 +55,17 @@ export class BaseAPI {
this.middleware = configuration.middleware;
}
withMiddleware = <T extends BaseAPI>(middlewares: Middleware[]) => {
const next = this.clone<T>();
withMiddleware = (middlewares: Middleware[]) => {
const next = this.clone();
next.middleware = next.middleware.concat(middlewares);
return next;
};
withPreMiddleware = <T extends BaseAPI>(preMiddlewares: Array<Middleware['pre']>) =>
this.withMiddleware<T>(preMiddlewares.map((pre) => ({ pre })));
withPreMiddleware = (preMiddlewares: Array<Middleware['pre']>) =>
this.withMiddleware(preMiddlewares.map((pre) => ({ pre })));
withPostMiddleware = <T extends BaseAPI>(postMiddlewares: Array<Middleware['post']>) =>
this.withMiddleware<T>(postMiddlewares.map((post) => ({ post })));
withPostMiddleware = (postMiddlewares: Array<Middleware['post']>) =>
this.withMiddleware(postMiddlewares.map((post) => ({ post })));
protected request = <T>(requestOpts: RequestOpts): Observable<T> =>
this.rxjsRequest(this.createRequestArgs(requestOpts)).pipe(
@@ -121,11 +115,14 @@ export class BaseAPI {
* Create a shallow clone of `this` by constructing a new instance
* and then shallow cloning data members.
*/
private clone = <T extends BaseAPI>(): T =>
private clone = (): BaseAPI =>
Object.assign(Object.create(Object.getPrototypeOf(this)), this);
}
// export for not being a breaking change
/**
* @deprecated
* export for not being a breaking change
*/
export class RequiredError extends Error {
name: 'RequiredError' = 'RequiredError';
}
@@ -142,7 +139,6 @@ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS'
export type HttpHeaders = { [key: string]: string };
export type HttpQuery = Partial<{ [key: string]: string | number | null | boolean | Array<string | number | null | boolean> }>; // partial is needed for strict mode
export type HttpBody = Json | FormData;
export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original';
export interface RequestOpts {
path: string;
@@ -167,12 +163,21 @@ const queryString = (params: HttpQuery): string => Object.keys(params)
// alias fallback for not being a breaking change
export const querystring = queryString;
/**
* @deprecated
*/
export const throwIfRequired = (params: {[key: string]: any}, key: string, nickname: string) => {
if (!params || params[key] === null || params[key] === undefined) {
if (!params || params[key] == null) {
throw new RequiredError(`Required parameter ${key} was null or undefined when calling ${nickname}.`);
}
};
export const throwIfNullOrUndefined = (value: any, nickname?: string) => {
if (value == null) {
throw new Error(`Parameter "${value}" was null or undefined when calling "${nickname}".`);
}
};
// alias for easier importing
export interface RequestArgs extends AjaxRequest {}
export interface ResponseArgs extends AjaxResponse {}