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-rxjs] refactor to arrow functions and short hand object creation #3077

Merged
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// tslint:disable
{{>licenseInfo}}
import { Observable } from 'rxjs';
import { BaseAPI, RequiredError, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime';
import { BaseAPI, throwIfRequired, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime';
{{#imports.0}}
import {
{{#imports}}
Expand Down Expand Up @@ -37,105 +37,83 @@ 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}}requestParameters: {{operationIdCamelCase}}Request{{/allParams.0}}): Observable<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> => {
{{#allParams}}
{{#required}}
if (requestParameters.{{paramName}} === null || requestParameters.{{paramName}} === undefined) {
throw new RequiredError('{{paramName}}','Required parameter requestParameters.{{paramName}} was null or undefined when calling {{nickname}}.');
}

throwIfRequired(requestParameters, '{{paramName}}', '{{nickname}}');
{{/required}}
{{/allParams}}
const queryParameters: HttpQuery = {};

{{#queryParams}}
{{#isListContainer}}
if (requestParameters.{{paramName}}) {
const headers: HttpHeaders = {
{{#bodyParam}}
{{^consumes}}
'Content-Type': 'application/json',
{{/consumes}}
{{#consumes.0}}
'Content-Type': '{{{mediaType}}}',
{{/consumes.0}}
{{/bodyParam}}
{{#headerParams}}
{{#isListContainer}}
...(requestParameters.{{paramName}} && { '{{baseName}}': requestParameters.{{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}'])) }),
{{/isListContainer}}
{{^isListContainer}}
...(requestParameters.{{paramName}} && { '{{baseName}}': String(requestParameters.{{paramName}}) }),
{{/isListContainer}}
{{/headerParams}}
{{#authMethods}}
{{#isBasic}}
...(this.configuration.username && this.configuration.password && { Authorization: `Basic ${btoa(this.configuration.username + ':' + this.configuration.password)}` }),
{{/isBasic}}
{{#isApiKey}}
{{#isKeyInHeader}}
...(this.configuration.apiKey && { '{{keyParamName}}': this.configuration.apiKey('{{keyParamName}}') }), // {{name}} authentication
{{/isKeyInHeader}}
{{/isApiKey}}
{{#isOAuth}}
// oauth required
...(this.configuration.accessToken && {
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('{{name}}', [{{#scopes}}'{{{scope}}}'{{^-last}}, {{/-last}}{{/scopes}}])
: this.configuration.accessToken)
}),
{{/isOAuth}}
{{/authMethods}}
};

const query: HttpQuery = {
{{#queryParams}}
{{#isListContainer}}
{{#isCollectionFormatMulti}}
queryParameters['{{baseName}}'] = requestParameters.{{paramName}};
...(requestParameters.{{paramName}} && { '{{baseName}}': requestParameters.{{paramName}} }),
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
queryParameters['{{baseName}}'] = requestParameters.{{paramName}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]);
...(requestParameters.{{paramName}} && { '{{baseName}}': requestParameters.{{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}']) }),
{{/isCollectionFormatMulti}}
}

{{/isListContainer}}
{{^isListContainer}}
if (requestParameters.{{paramName}} !== undefined && requestParameters.{{paramName}} !== null) {
{{/isListContainer}}
{{^isListContainer}}
{{#isDateTime}}
queryParameters['{{baseName}}'] = (requestParameters.{{paramName}} as any).toISOString();
...(requestParameters.{{paramName}} && { '{{baseName}}': (requestParameters.{{paramName}} as any).toISOString() }),
{{/isDateTime}}
{{^isDateTime}}
{{#isDate}}
queryParameters['{{baseName}}'] = (requestParameters.{{paramName}} as any).toISOString();
...(requestParameters.{{paramName}} && { '{{baseName}}': (requestParameters.{{paramName}} as any).toISOString() }),
{{/isDate}}
{{^isDate}}
queryParameters['{{baseName}}'] = requestParameters.{{paramName}};
...(requestParameters.{{paramName}} && { '{{baseName}}': requestParameters.{{paramName}} }),
{{/isDate}}
{{/isDateTime}}
}

{{/isListContainer}}
{{/queryParams}}
const headerParameters: HttpHeaders = {};
{{/isListContainer}}
{{/queryParams}}
{{#authMethods}}
{{#isApiKey}}
{{#isKeyInQuery}}
...(this.configuration.apiKey && { '{{keyParamName}}': this.configuration.apiKey && this.configuration.apiKey('{{keyParamName}}') }), // {{name}} authentication
{{/isKeyInQuery}}
{{/isApiKey}}
{{/authMethods}}
};

{{#bodyParam}}
{{^consumes}}
headerParameters['Content-Type'] = 'application/json';

{{/consumes}}
{{#consumes.0}}
headerParameters['Content-Type'] = '{{{mediaType}}}';

{{/consumes.0}}
{{/bodyParam}}
{{#headerParams}}
{{#isListContainer}}
if (requestParameters.{{paramName}}) {
headerParameters['{{baseName}}'] = requestParameters.{{paramName}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]));
}

{{/isListContainer}}
{{^isListContainer}}
if (requestParameters.{{paramName}} !== undefined && requestParameters.{{paramName}} !== null) {
headerParameters['{{baseName}}'] = String(requestParameters.{{paramName}});
}

{{/isListContainer}}
{{/headerParams}}
{{#authMethods}}
{{#isBasic}}
if (this.configuration && (this.configuration.username !== undefined || this.configuration.password !== undefined)) {
headerParameters["Authorization"] = "Basic " + btoa(this.configuration.username + ":" + this.configuration.password);
}

{{/isBasic}}
{{#isApiKey}}
{{#isKeyInHeader}}
if (this.configuration && this.configuration.apiKey) {
headerParameters["{{keyParamName}}"] = this.configuration.apiKey("{{keyParamName}}"); // {{name}} authentication
}

{{/isKeyInHeader}}
{{#isKeyInQuery}}
if (this.configuration && this.configuration.apiKey) {
queryParameters["{{keyParamName}}"] = this.configuration.apiKey("{{keyParamName}}"); // {{name}} authentication
}

{{/isKeyInQuery}}
{{/isApiKey}}
{{#isOAuth}}
if (this.configuration && this.configuration.accessToken) {
// oauth required
if (typeof this.configuration.accessToken === 'function') {
headerParameters["Authorization"] = this.configuration.accessToken("{{name}}", [{{#scopes}}"{{{scope}}}"{{^-last}}, {{/-last}}{{/scopes}}]);
} else {
headerParameters["Authorization"] = this.configuration.accessToken;
}
}

{{/isOAuth}}
{{/authMethods}}
{{#hasFormParams}}
const formData = new FormData();
{{/hasFormParams}}
Expand All @@ -148,7 +126,7 @@ export class {{classname}} extends BaseAPI {
})
{{/isCollectionFormatMulti}}
{{^isCollectionFormatMulti}}
formData.append('{{baseName}}', requestParameters.{{paramName}}.join(COLLECTION_FORMATS["{{collectionFormat}}"]));
formData.append('{{baseName}}', requestParameters.{{paramName}}.join(COLLECTION_FORMATS['{{collectionFormat}}']));
{{/isCollectionFormatMulti}}
}

Expand All @@ -161,10 +139,10 @@ export class {{classname}} extends BaseAPI {
{{/isListContainer}}
{{/formParams}}
return this.request<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}>({
path: `{{{path}}}`{{#pathParams}}.replace(`{${"{{baseName}}"}}`, encodeURIComponent(String(requestParameters.{{paramName}}))){{/pathParams}},
path: `{{{path}}}`{{#pathParams}}.replace({{=<% %>=}}`{<%baseName%>}`<%={{ }}=%>, encodeURIComponent(String(requestParameters.{{paramName}}))){{/pathParams}},
method: '{{httpMethod}}',
headers: headerParameters,
query: queryParameters,
headers,
query,
{{#hasBodyParam}}
{{#bodyParam}}
{{#isContainer}}
Expand Down Expand Up @@ -196,9 +174,9 @@ export class {{classname}} extends BaseAPI {
{{#allParams}}
{{#isEnum}}
/**
* @export
* @enum {string}
*/
* @export
* @enum {string}
*/
export enum {{operationIdCamelCase}}{{enumName}} {
{{#allowableValues}}
{{#enumVars}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,46 +55,41 @@ export class Configuration {
* This is the base class for all generated API classes.
*/
export class BaseAPI {
private middleware: Middleware[];
private middleware: Middleware[] = [];

constructor(protected configuration = new Configuration()) {
this.middleware = configuration.middleware;
}

withMiddleware<T extends BaseAPI>(this: T, ...middlewares: Middleware[]) {
withMiddleware = <T extends BaseAPI>(middlewares: Middleware[]) => {
const next = this.clone<T>();
next.middleware = next.middleware.concat(...middlewares);
next.middleware = next.middleware.concat(middlewares);
return next;
}

withPreMiddleware<T extends BaseAPI>(this: T, ...preMiddlewares: Array<Middleware['pre']>) {
const middlewares = preMiddlewares.map((pre) => ({ pre }));
return this.withMiddleware<T>(...middlewares);
}
withPreMiddleware = <T extends BaseAPI>(preMiddlewares: Array<Middleware['pre']>) =>
this.withMiddleware<T>(preMiddlewares.map((pre) => ({ pre })));

withPostMiddleware<T extends BaseAPI>(this: T, ...postMiddlewares: Array<Middleware['post']>) {
const middlewares = postMiddlewares.map((post) => ({ post }));
return this.withMiddleware<T>(...middlewares);
}
withPostMiddleware = <T extends BaseAPI>(postMiddlewares: Array<Middleware['post']>) =>
this.withMiddleware<T>(postMiddlewares.map((post) => ({ post })));

protected request<T>(context: RequestOpts): Observable<T> {
return this.rxjsRequest(this.createRequestArgs(context)).pipe(
protected request = <T>(context: RequestOpts): Observable<T> =>
this.rxjsRequest(this.createRequestArgs(context)).pipe(
map((res) => {
if (res.status >= 200 && res.status < 300) {
return res.response as T;
}
throw res;
})
);
}

private createRequestArgs(context: RequestOpts): RequestArgs {
private createRequestArgs = (context: RequestOpts): RequestArgs => {
let url = this.configuration.basePath + context.path;
if (context.query !== undefined && Object.keys(context.query).length !== 0) {
// only add the querystring to the URL if there are query parameters.
// only add the queryString to the URL if there are query parameters.
// this is done to avoid urls ending with a '?' character which buggy webservers
// do not handle correctly sometimes.
url += '?' + querystring(context.query);
url += '?' + queryString(context.query);
}
const body = context.body instanceof FormData ? context.body : JSON.stringify(context.body);
const options = {
Expand All @@ -105,9 +100,9 @@ export class BaseAPI {
return { url, options };
}

private rxjsRequest(params: RequestContext): Observable<AjaxResponse> {
const preMiddlewares = this.middleware && this.middleware.filter((item) => item.pre);
const postMiddlewares = this.middleware && this.middleware.filter((item) => item.post);
private rxjsRequest = (params: RequestContext): Observable<AjaxResponse> => {
const preMiddlewares = this.middleware.filter((item) => item.pre);
const postMiddlewares = this.middleware.filter((item) => item.post);

return of(params).pipe(
map((args) => {
Expand All @@ -133,19 +128,13 @@ 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>(this: T): T {
const constructor = this.constructor as any;
const next = new constructor(this.configuration);
next.middleware = this.middleware.slice();
return next;
}
private clone = <T extends BaseAPI>(): T =>
Object.assign(Object.create(Object.getPrototypeOf(this)), this)
}

// export for not being a breaking change
export class RequiredError extends Error {
name: 'RequiredError' = 'RequiredError';
constructor(public field: string, msg?: string) {
super(msg);
}
}

export const COLLECTION_FORMATS = {
Expand Down Expand Up @@ -175,17 +164,24 @@ export interface RequestOpts {
body?: HttpBody;
}

export function querystring(params: HttpQuery): string {
return Object.keys(params)
.map((key) => {
const value = params[key];
if (value instanceof Array) {
return value.map((val) => `${encodeURIComponent(key)}=${encodeURIComponent(String(val))}`)
.join('&');
}
return `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`;
})
.join('&');
const queryString = (params: HttpQuery): string => Object.keys(params)
.map((key) => {
const value = params[key];
if (value instanceof Array) {
return value.map((val) => `${encodeURIComponent(key)}=${encodeURIComponent(String(val))}`)
.join('&');
}
return `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`;
})
.join('&');

// alias fallback for not being a breaking change
Copy link
Member

Choose a reason for hiding this comment

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

nice

export const querystring = queryString;

export const throwIfRequired = (params: {[key: string]: any}, key: string, nickname: string) => {
if (!params || params[key] === null || params[key] === undefined) {
throw new RequiredError(`Required parameter ${key} was null or undefined when calling ${nickname}.`);
}
}

export interface RequestContext extends RequestArgs {}
Expand Down
Loading