Skip to content

Add optional erasable syntax configuration to Typescript generator. #21040

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions docs/generators/typescript.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true|
|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true|
|supportsES6|Generate code that conforms to ES6.| |false|
|useErasableSyntax|Use erasable syntax for the generated code. This is a temporary feature and will be removed in the future.| |false|
|useInversify|Enable this to generate decorators and service identifiers for the InversifyJS inversion of control container. If you set 'deno' as 'platform', the generator will process this value as 'disable'.| |false|
|useObjectParameters|Use aggregate parameter objects as function arguments for api operations instead of passing each parameter as a separate function argument.| |false|
|useRxJS|Enable this to internally use rxjs observables. If disabled, a stub is used instead. This is required for the 'angular' framework.| |false|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ public class TypeScriptClientCodegen extends AbstractTypeScriptClientCodegen imp
private static final String USE_OBJECT_PARAMS_SWITCH = "useObjectParameters";
private static final String USE_OBJECT_PARAMS_DESC = "Use aggregate parameter objects as function arguments for api operations instead of passing each parameter as a separate function argument.";

public static final String USE_ERASABLE_SYNTAX = "useErasableSyntax";
public static final String USE_ERASABLE_SYNTAX_DESC = "Use erasable syntax for the generated code. This is a temporary feature and will be removed in the future.";

private final Map<String, String> frameworkToHttpLibMap;

// NPM Options
Expand Down Expand Up @@ -122,6 +125,7 @@ public TypeScriptClientCodegen() {
cliOptions.add(new CliOption(TypeScriptClientCodegen.USE_OBJECT_PARAMS_SWITCH, TypeScriptClientCodegen.USE_OBJECT_PARAMS_DESC).defaultValue("false"));
cliOptions.add(new CliOption(TypeScriptClientCodegen.USE_INVERSIFY_SWITCH, TypeScriptClientCodegen.USE_INVERSIFY_SWITCH_DESC).defaultValue("false"));
cliOptions.add(new CliOption(TypeScriptClientCodegen.IMPORT_FILE_EXTENSION_SWITCH, TypeScriptClientCodegen.IMPORT_FILE_EXTENSION_SWITCH_DESC));
cliOptions.add(new CliOption(TypeScriptClientCodegen.USE_ERASABLE_SYNTAX, TypeScriptClientCodegen.USE_ERASABLE_SYNTAX_DESC).defaultValue("false"));

CliOption frameworkOption = new CliOption(TypeScriptClientCodegen.FRAMEWORK_SWITCH, TypeScriptClientCodegen.FRAMEWORK_SWITCH_DESC);
for (String option : TypeScriptClientCodegen.FRAMEWORKS) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,20 @@
*
*/
export class ServerConfiguration<T extends { [key: string]: string }> {
{{^useErasableSyntax}}
public constructor(private url: string, private variableConfiguration: T, private description: string) {}
{{/useErasableSyntax}}
{{#useErasableSyntax}}
private url: string;
private variableConfiguration: T;
private description: string;

public constructor(url: string, variableConfiguration: T, description: string) {
this.url = url;
this.variableConfiguration = variableConfiguration;
this.description = description;
}
{{/useErasableSyntax}}

/**
* Sets the value of the variables of this server.
Expand All @@ -25,15 +38,15 @@ export class ServerConfiguration<T extends { [key: string]: string }> {
}

/**
* Constructions the URL this server using the url with variables
* replaced with their respective values
* Constructs the URL for this server using the url with variables
* replaced with their respective values.
*/
public getUrl(): string {
let replacedUrl = this.url;
for (const key in this.variableConfiguration) {
if (this.variableConfiguration.hasOwnProperty(key)) {
const re = new RegExp("{" + key + "}","g");
replacedUrl = replacedUrl.replace(re, this.variableConfiguration[key]);
const re = new RegExp("{" + key + "}", "g");
replacedUrl = replacedUrl.replace(re, this.variableConfiguration[key]);
}
}
return replacedUrl;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,16 @@ export const COLLECTION_FORMATS = {
{{/useInversify}}
export class BaseAPIRequestFactory {

{{^useErasableSyntax}}
constructor({{#useInversify}}@inject(AbstractConfiguration) {{/useInversify}}protected configuration: Configuration) {
}
{{/useErasableSyntax}}
{{#useErasableSyntax}}
protected configuration: Configuration;
constructor({{#useInversify}}@inject(AbstractConfiguration) {{/useInversify}} config: Configuration) {
this.configuration = config;
}
{{/useErasableSyntax}}
};

/**
Expand All @@ -38,7 +46,20 @@ export class BaseAPIRequestFactory {
*/
export class RequiredError extends Error {
override name: "RequiredError" = "RequiredError";
{{#useErasableSyntax}}
public api: string;
public method: string;
public field: string;
constructor(api: string, method: string, field: string) {
super("Required parameter " + field + " was null or undefined when calling " + api + "." + method + ".");
this.api = api;
this.method = method;
this.field = field;
}
{{/useErasableSyntax}}
{{^useErasableSyntax}}
constructor(public api: string, public method: string, public field: string) {
super("Required parameter " + field + " was null or undefined when calling " + api + "." + method + ".");
}
{{/useErasableSyntax}}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,22 @@
*
*/
export class ApiException<T> extends Error {
{{#useErasableSyntax}}
public code: number;
public body: T;
public headers: { [key: string]: string; };
public constructor(code: number, message: string, body: T, headers: { [key: string]: string; }) {
super("HTTP-Code: " + code + "\nMessage: " + message + "\nBody: " + JSON.stringify(body) + "\nHeaders: " +
JSON.stringify(headers));
this.code = code;
this.body = body;
this.headers = headers;
}
{{/useErasableSyntax}}
{{^useErasableSyntax}}
public constructor(public code: number, message: string, public body: T, public headers: { [key: string]: string; }) {
super("HTTP-Code: " + code + "\nMessage: " + message + "\nBody: " + JSON.stringify(body) + "\nHeaders: " +
JSON.stringify(headers))
JSON.stringify(headers));
}
}
{{/useErasableSyntax}}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,15 @@ export interface Middleware {
}

export class PromiseMiddlewareWrapper implements Middleware {

public constructor(private middleware: PromiseMiddleware) {

{{#useErasableSyntax}}
private middleware: PromiseMiddleware;
public constructor(middleware: PromiseMiddleware) {
this.middleware = middleware;
}
{{/useErasableSyntax}}
{{^useErasableSyntax}}
public constructor(private middleware: PromiseMiddleware) {}
{{/useErasableSyntax}}

pre(context: RequestContext): Observable<RequestContext> {
return from(this.middleware.pre(context));
Expand All @@ -38,7 +43,6 @@ export class PromiseMiddlewareWrapper implements Middleware {
post(context: ResponseContext): Observable<ResponseContext> {
return from(this.middleware.post(context));
}

}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,28 @@ export interface TokenProvider {
{{/useInversify}}
export class {{#lambda.pascalcase}}{{name}}{{/lambda.pascalcase}}Authentication implements SecurityAuthentication {
{{#isApiKey}}
{{^useErasableSyntax}}
/**
* Configures this api key authentication with the necessary properties
*
* @param apiKey: The api key to be used for every request
*/
public constructor({{#useInversify}}@inject(AuthApiKey) @named("{{name}}") {{/useInversify}}private apiKey: string) {}
{{/useErasableSyntax}}
{{#useErasableSyntax}}
private apiKey: string;
/**
* Configures this api key authentication with the necessary properties
*
* @param apiKey: The api key to be used for every request
*/
public constructor({{#useInversify}}@inject(AuthApiKey) @named("{{name}}") {{/useInversify}}apiKey: string) {
this.apiKey = apiKey;
}
{{/useErasableSyntax}}
{{/isApiKey}}
{{#isBasicBasic}}
{{^useErasableSyntax}}
/**
* Configures the http authentication with the required details.
*
Expand All @@ -58,22 +72,66 @@ export class {{#lambda.pascalcase}}{{name}}{{/lambda.pascalcase}}Authentication
{{#useInversify}}@inject(AuthUsername) @named("{{name}}") {{/useInversify}}private username: string,
{{#useInversify}}@inject(AuthPassword) @named("{{name}}") {{/useInversify}}private password: string
) {}
{{/useErasableSyntax}}
{{#useErasableSyntax}}
private username: string;
private password: string;
/**
* Configures the http authentication with the required details.
*
* @param username username for http basic authentication
* @param password password for http basic authentication
*/
public constructor(
{{#useInversify}}@inject(AuthUsername) @named("{{name}}") {{/useInversify}}username: string,
{{#useInversify}}@inject(AuthPassword) @named("{{name}}") {{/useInversify}}password: string
) {
this.username = username;
this.password = password;
}
{{/useErasableSyntax}}
{{/isBasicBasic}}
{{#isBasicBearer}}
{{^useErasableSyntax}}
/**
* Configures the http authentication with the required details.
*
* @param tokenProvider service that can provide the up-to-date token when needed
*/
public constructor({{#useInversify}}@inject(AbstractTokenProvider) @named("{{name}}") {{/useInversify}}private tokenProvider: TokenProvider) {}
{{/useErasableSyntax}}
{{#useErasableSyntax}}
private tokenProvider: TokenProvider;
/**
* Configures the http authentication with the required details.
*
* @param tokenProvider service that can provide the up-to-date token when needed
*/
public constructor({{#useInversify}}@inject(AbstractTokenProvider) @named("{{name}}") {{/useInversify}}tokenProvider: TokenProvider) {
this.tokenProvider = tokenProvider;
}
{{/useErasableSyntax}}
{{/isBasicBearer}}
{{#isOAuth}}
{{^useErasableSyntax}}
/**
* Configures OAuth2 with the necessary properties
*
* @param accessToken: The access token to be used for every request
*/
public constructor(private accessToken: string) {}
{{/useErasableSyntax}}
{{#useErasableSyntax}}
private accessToken: string;
/**
* Configures OAuth2 with the necessary properties
*
* @param accessToken: The access token to be used for every request
*/
public constructor(accessToken: string) {
this.accessToken = accessToken;
}
{{/useErasableSyntax}}
{{/isOAuth}}

public getName(): string {
Expand All @@ -98,7 +156,6 @@ export class {{#lambda.pascalcase}}{{name}}{{/lambda.pascalcase}}Authentication
}

{{/authMethods}}

export type AuthMethods = {
{{^useInversify}}
"default"?: SecurityAuthentication,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,22 @@ export * from './jquery{{importFileExtension}}';
/**
* Represents an HTTP method.
*/
{{#useErasableSyntax}}
export const HttpMethod = {
GET: "GET",
HEAD: "HEAD",
POST: "POST",
PUT: "PUT",
DELETE: "DELETE",
CONNECT: "CONNECT",
OPTIONS: "OPTIONS",
TRACE: "TRACE",
PATCH: "PATCH"
} as const;

export type HttpMethod = typeof HttpMethod[keyof typeof HttpMethod];
{{/useErasableSyntax}}
{{^useErasableSyntax}}
export enum HttpMethod {
GET = "GET",
HEAD = "HEAD",
Expand All @@ -36,6 +52,7 @@ export enum HttpMethod {
TRACE = "TRACE",
PATCH = "PATCH"
}
{{/useErasableSyntax}}

/**
* Represents an HTTP file which will be transferred from or to a server.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
export class Observable<T> {
{{#useErasableSyntax}}
private promise: Promise<T>;
constructor(promise: Promise<T>) {
this.promise = promise;
}
{{/useErasableSyntax}}
{{^useErasableSyntax}}
constructor(private promise: Promise<T>) {}
{{/useErasableSyntax}}

toPromise() {
return this.promise;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
Expand Down Expand Up @@ -210,4 +212,32 @@ public void testForAllSanitizedEnum() throws Exception {
"}"
);
}
}

@Test(description = "Verify useErasableSyntax config parameter generates erasable code")
public void testUseErasableSyntaxConfig() throws IOException {
boolean[] options = {true, false};
for (boolean useErasableSyntax : options) {
final File output = Files.createTempDirectory("typescriptnodeclient_").toFile();
output.deleteOnExit();

final CodegenConfigurator configurator = new CodegenConfigurator()
.setGeneratorName("typescript")
.setInputSpec("src/test/resources/3_0/composed-schemas.yaml")
.addAdditionalProperty("useErasableSyntax", useErasableSyntax)
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));

final ClientOptInput clientOptInput = configurator.toClientOptInput();
final DefaultGenerator generator = new DefaultGenerator();
final List<File> files = generator.opts(clientOptInput).generate();
files.forEach(File::deleteOnExit);

Path serverConfigurationPath = Paths.get(output + "/apis/baseapi.ts");
TestUtils.assertFileExists(serverConfigurationPath);
if (useErasableSyntax) {
TestUtils.assertFileContains(serverConfigurationPath, "this.configuration = config;"); // Check for erasable syntax
} else {
TestUtils.assertFileNotContains(serverConfigurationPath, "this.configuration = config;"); // Check for non-erasable syntax
}
}
}
}
4 changes: 2 additions & 2 deletions samples/client/echo_api/typescript/build/apis/exception.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion samples/client/echo_api/typescript/build/auth/auth.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 1 addition & 5 deletions samples/client/echo_api/typescript/build/middleware.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading