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-angular] refactor service classes for reducing bundle sizes by ~20% #20681

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
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ public void processOpts() {
supportingFiles.add(new SupportingFile("index.mustache", getIndexDirectory(), "index.ts"));
supportingFiles.add(new SupportingFile("api.module.mustache", getIndexDirectory(), "api.module.ts"));
supportingFiles.add(new SupportingFile("configuration.mustache", getIndexDirectory(), "configuration.ts"));
supportingFiles.add(new SupportingFile("api.base.service.mustache", getIndexDirectory(), "api.base.service.ts"));
supportingFiles.add(new SupportingFile("variables.mustache", getIndexDirectory(), "variables.ts"));
supportingFiles.add(new SupportingFile("encoder.mustache", getIndexDirectory(), "encoder.ts"));
supportingFiles.add(new SupportingFile("param.mustache", getIndexDirectory(), "param.ts"));
Expand Down Expand Up @@ -411,7 +412,10 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap operations, L
hasSomeFormParams = true;
}
op.httpMethod = op.httpMethod.toLowerCase(Locale.ENGLISH);

// deduplicate auth methods by name (as they will lead to duplicate code):
op.authMethods =
op.authMethods != null ? op.authMethods.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(x -> x.name))), ArrayList::new))
: null;

// Prep a string buffer where we're going to set up our new version of the string.
StringBuilder pathBuffer = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { HttpClient, HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http';
import { CustomHttpParameterCodec } from './encoder';
import { {{configurationClassName}} } from './configuration';

export class BaseService {
protected basePath = '';
public defaultHeaders = new HttpHeaders();
public configuration: {{configurationClassName}};
public encoder: HttpParameterCodec;

constructor(protected httpClient: HttpClient, basePath?: string|string[], configuration?: {{configurationClassName}}) {
this.configuration = configuration || new {{configurationClassName}}();
if (typeof this.configuration.basePath !== 'string') {
const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined;
if (firstBasePath != undefined) {
basePath = firstBasePath;
}

if (typeof basePath !== 'string') {
basePath = this.basePath;
}
this.configuration.basePath = basePath;
}
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
}

protected canConsumeForm(consumes: string[]): boolean {
return consumes.indexOf('multipart/form-data') !== -1;
}

protected addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams {
// If the value is an object (but not a Date), recursively add its keys.
if (typeof value === 'object' && !(value instanceof Date)) {
return this.addToHttpParamsRecursive(httpParams, value, key);
}
return this.addToHttpParamsRecursive(httpParams, value, key);
}

protected addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams {
if (value === null || value === undefined) {
return httpParams;
}
if (typeof value === 'object') {
// If JSON format is preferred, key must be provided.
if (key != null) {
return httpParams.append(key, JSON.stringify(value));
}
// Otherwise, if it's an array, add each element.
if (Array.isArray(value)) {
value.forEach(elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key));
} else if (value instanceof Date) {
if (key != null) {
httpParams = httpParams.append(key, value.toISOString());
} else {
throw Error("key may not be null if value is Date");
}
} else {
Object.keys(value).forEach(k => {
const paramKey = key ? `${key}.${k}` : k;
httpParams = this.addToHttpParamsRecursive(httpParams, value[k], paramKey);
});
}
return httpParams;
} else if (key != null) {
return httpParams.append(key, value);
}
throw Error("key may not be null if value is not object or array");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { {{ classname }} } from '{{ filename }}';
// @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { {{configurationClassName}} } from '../configuration';
import { BaseService } from '../api.base.service';
{{#withInterfaces}}
import {
{{classname}}Interface{{#useSingleRequestParameter}}{{#operations}}{{#operation}}{{#allParams.0}},
Expand Down Expand Up @@ -55,99 +56,14 @@ export interface {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterIn
})
{{/isProvidedInNone}}
{{#withInterfaces}}
export class {{classname}} implements {{classname}}Interface {
export class {{classname}} extends BaseService implements {{classname}}Interface {
{{/withInterfaces}}
{{^withInterfaces}}
export class {{classname}} {
export class {{classname}} extends BaseService {
{{/withInterfaces}}

protected basePath = '{{{basePath}}}';
public defaultHeaders = new HttpHeaders();
public configuration = new {{configurationClassName}}();
public encoder: HttpParameterCodec;

constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string|string[], @Optional() configuration: {{configurationClassName}}) {
if (configuration) {
this.configuration = configuration;
}
if (typeof this.configuration.basePath !== 'string') {
const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined;
if (firstBasePath != undefined) {
basePath = firstBasePath;
}

if (typeof basePath !== 'string') {
basePath = this.basePath;
}
this.configuration.basePath = basePath;
}
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
}

{{#hasSomeFormParams}}
/**
* @param consumes string[] mime-types
* @return true: consumes contains 'multipart/form-data', false: otherwise
*/
private canConsumeForm(consumes: string[]): boolean {
const form = 'multipart/form-data';
for (const consume of consumes) {
if (form === consume) {
return true;
}
}
return false;
}
{{/hasSomeFormParams}}

// @ts-ignore
private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams {
{{#isQueryParamObjectFormatJson}}
httpParams = this.addToHttpParamsRecursive(httpParams, value, key);
{{/isQueryParamObjectFormatJson}}
{{^isQueryParamObjectFormatJson}}
if (typeof value === "object" && value instanceof Date === false) {
httpParams = this.addToHttpParamsRecursive(httpParams, value);
} else {
httpParams = this.addToHttpParamsRecursive(httpParams, value, key);
}
{{/isQueryParamObjectFormatJson}}
return httpParams;
}

private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams {
if (value == null) {
return httpParams;
}

if (typeof value === "object") {
{{#isQueryParamObjectFormatJson}}
if (key != null) {
httpParams = httpParams.append(key, JSON.stringify(value));
} else {
throw Error("key may not be null if value is a QueryParamObject");
}
{{/isQueryParamObjectFormatJson}}
{{^isQueryParamObjectFormatJson}}
if (Array.isArray(value)) {
(value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key));
} else if (value instanceof Date) {
if (key != null) {
httpParams = httpParams.append(key, (value as Date).toISOString(){{^isDateTime}}.substring(0, 10){{/isDateTime}});
} else {
throw Error("key may not be null if value is Date");
}
} else {
Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive(
httpParams, value[k], key != null ? `${key}{{#isQueryParamObjectFormatDot}}.{{/isQueryParamObjectFormatDot}}{{#isQueryParamObjectFormatKey}}[{{/isQueryParamObjectFormatKey}}${k}{{#isQueryParamObjectFormatKey}}]{{/isQueryParamObjectFormatKey}}` : k));
}
{{/isQueryParamObjectFormatJson}}
} else if (key != null) {
httpParams = httpParams.append(key, value);
} else {
throw Error("key may not be null if value is not object or array");
}
return httpParams;
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: {{configurationClassName}}) {
super(httpClient, basePath, configuration);
}

{{#operation}}
Expand Down Expand Up @@ -213,10 +129,8 @@ export class {{classname}} {
}
{{/isArray}}
{{^isArray}}
if ({{paramName}} !== undefined && {{paramName}} !== null) {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>{{paramName}}, '{{baseName}}');
}
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>{{paramName}}, '{{baseName}}');
{{/isArray}}
{{/queryParams}}

Expand All @@ -236,60 +150,43 @@ export class {{classname}} {
{{/headerParams}}

{{#authMethods}}
{{#-first}}
let localVarCredential: string | undefined;
{{/-first}}
// authentication ({{name}}) required
localVarCredential = this.configuration.lookupCredential('{{name}}');
if (localVarCredential) {
{{#isApiKey}}
{{#isKeyInHeader}}
localVarHeaders = localVarHeaders.set('{{keyParamName}}', localVarCredential);
localVarHeaders = this.configuration.addCredentialToHeaders('{{name}}', '{{keyParamName}}', localVarHeaders);
{{/isKeyInHeader}}
{{#isKeyInQuery}}
localVarQueryParameters = localVarQueryParameters.set('{{keyParamName}}', localVarCredential);
localVarQueryParameters = this.configuration.addCredentialToQuery('{{name}}', '{{keyParamName}}', localVarQueryParameters);
{{/isKeyInQuery}}
{{/isApiKey}}
{{#isBasic}}
{{#isBasicBasic}}
localVarHeaders = localVarHeaders.set('Authorization', 'Basic ' + localVarCredential);
localVarHeaders = this.configuration.addCredentialToHeaders('{{name}}', 'Authorization', localVarHeaders, 'Basic ');
{{/isBasicBasic}}
{{#isBasicBearer}}
localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential);
localVarHeaders = this.configuration.addCredentialToHeaders('{{name}}', 'Authorization', localVarHeaders, 'Bearer ');
{{/isBasicBearer}}
{{/isBasic}}
{{#isOAuth}}
localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential);
localVarHeaders = this.configuration.addCredentialToHeaders('{{name}}', 'Authorization', localVarHeaders, 'Bearer ');
{{/isOAuth}}
}

{{/authMethods}}
let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept;
if (localVarHttpHeaderAcceptSelected === undefined) {
// to determine the Accept header
const httpHeaderAccepts: string[] = [
{{#produces}}
'{{{mediaType}}}'{{^-last}},{{/-last}}
{{/produces}}
];
localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts);
}
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
{{#produces}}
'{{{mediaType}}}'{{^-last}},{{/-last}}
{{/produces}}
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}

{{#httpContextInOptions}}
let localVarHttpContext: HttpContext | undefined = options && options.context;
if (localVarHttpContext === undefined) {
localVarHttpContext = new HttpContext();
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
{{/httpContextInOptions}}
{{#httpTransferCacheInOptions}}

let localVarTransferCache: boolean | undefined = options && options.transferCache;
if (localVarTransferCache === undefined) {
localVarTransferCache = true;
}
const localVarTransferCache: boolean = options?.transferCache ?? true;
{{/httpTransferCacheInOptions}}

{{#bodyParam}}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { HttpParameterCodec } from '@angular/common/http';
import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http';
import { Param } from './param';

export interface {{configurationParametersInterfaceName}} {
Expand Down Expand Up @@ -187,6 +187,20 @@ export class {{configurationClassName}} {
: value;
}

public addCredentialToHeaders(credentialKey: string, headerName: string, headers: HttpHeaders, prefix?: string): HttpHeaders {
const value = this.lookupCredential(credentialKey);
return value
? headers.set(headerName, (prefix ?? '') + value)
: headers;
}

public addCredentialToQuery(credentialKey: string, paramName: string, query: HttpParams): HttpParams {
const value = this.lookupCredential(credentialKey);
return value
? query.set(paramName, value)
: query;
}

private defaultEncodeParam(param: Param): string {
// This implementation exists as fallback for missing configuration
// and for backwards compatibility to older typescript-angular generator versions.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
Expand Down Expand Up @@ -390,4 +391,28 @@ public void testAngularDependenciesFromConfigFile() {
assertThat(codegen.additionalProperties()).containsEntry("ngPackagrVersion", "19.0.0");
assertThat(codegen.additionalProperties()).containsEntry("zonejsVersion", "0.15.0");
}

@Test
public void testNoDuplicateAuthentication() throws IOException {
// GIVEN
final String specPath = "src/test/resources/3_0/spring/petstore-auth.yaml";

File output = Files.createTempDirectory("test").toFile();
output.deleteOnExit();

// WHEN
final CodegenConfigurator configurator = new CodegenConfigurator()
.setGeneratorName("typescript-angular")
.setInputSpec(specPath)
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));

final ClientOptInput clientOptInput = configurator.toClientOptInput();

Generator generator = new DefaultGenerator();
generator.opts(clientOptInput).generate();

// THEN
final String fileContents = Files.readString(Paths.get(output + "/api/default.service.ts"));
assertThat(fileContents).containsOnlyOnce("localVarHeaders = this.configuration.addCredentialToHeaders('OAuth2', 'Authorization', localVarHeaders, 'Bearer ');");
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
.gitignore
README.md
api.base.service.ts
api.module.ts
api/api.ts
api/pet.service.ts
Expand Down
Loading
Loading