diff --git a/modules/openapi-generator/src/main/resources/typescript-rxjs/apis.mustache b/modules/openapi-generator/src/main/resources/typescript-rxjs/apis.mustache index c394a87f2833..fe486821daf4 100644 --- a/modules/openapi-generator/src/main/resources/typescript-rxjs/apis.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-rxjs/apis.mustache @@ -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}} @@ -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}} @@ -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}} } @@ -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}} @@ -196,9 +174,9 @@ export class {{classname}} extends BaseAPI { {{#allParams}} {{#isEnum}} /** - * @export - * @enum {string} - */ + * @export + * @enum {string} + */ export enum {{operationIdCamelCase}}{{enumName}} { {{#allowableValues}} {{#enumVars}} diff --git a/modules/openapi-generator/src/main/resources/typescript-rxjs/runtime.mustache b/modules/openapi-generator/src/main/resources/typescript-rxjs/runtime.mustache index a36447023127..19f893b62d34 100644 --- a/modules/openapi-generator/src/main/resources/typescript-rxjs/runtime.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-rxjs/runtime.mustache @@ -55,30 +55,26 @@ 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(this: T, ...middlewares: Middleware[]) { + withMiddleware = (middlewares: Middleware[]) => { const next = this.clone(); - next.middleware = next.middleware.concat(...middlewares); + next.middleware = next.middleware.concat(middlewares); return next; } - withPreMiddleware(this: T, ...preMiddlewares: Array) { - const middlewares = preMiddlewares.map((pre) => ({ pre })); - return this.withMiddleware(...middlewares); - } + withPreMiddleware = (preMiddlewares: Array) => + this.withMiddleware(preMiddlewares.map((pre) => ({ pre }))); - withPostMiddleware(this: T, ...postMiddlewares: Array) { - const middlewares = postMiddlewares.map((post) => ({ post })); - return this.withMiddleware(...middlewares); - } + withPostMiddleware = (postMiddlewares: Array) => + this.withMiddleware(postMiddlewares.map((post) => ({ post }))); - protected request(context: RequestOpts): Observable { - return this.rxjsRequest(this.createRequestArgs(context)).pipe( + protected request = (context: RequestOpts): Observable => + this.rxjsRequest(this.createRequestArgs(context)).pipe( map((res) => { if (res.status >= 200 && res.status < 300) { return res.response as T; @@ -86,15 +82,14 @@ export class BaseAPI { 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 = { @@ -105,9 +100,9 @@ export class BaseAPI { return { url, options }; } - private rxjsRequest(params: RequestContext): Observable { - 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 => { + const preMiddlewares = this.middleware.filter((item) => item.pre); + const postMiddlewares = this.middleware.filter((item) => item.post); return of(params).pipe( map((args) => { @@ -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(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 => + 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 = { @@ -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 +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 {} diff --git a/samples/client/petstore/typescript-rxjs/builds/default/apis/PetApi.ts b/samples/client/petstore/typescript-rxjs/builds/default/apis/PetApi.ts index dab74f1d7bf1..8f8db90ce78a 100644 --- a/samples/client/petstore/typescript-rxjs/builds/default/apis/PetApi.ts +++ b/samples/client/petstore/typescript-rxjs/builds/default/apis/PetApi.ts @@ -12,7 +12,7 @@ */ import { Observable } from 'rxjs'; -import { BaseAPI, RequiredError, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; +import { BaseAPI, throwIfRequired, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; import { ApiResponse, Pet, @@ -63,31 +63,27 @@ export class PetApi extends BaseAPI { /** * Add a new pet to the store */ - addPet(requestParameters: AddPetRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling addPet.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + addPet = (requestParameters: AddPetRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'addPet'); - headerParameters['Content-Type'] = 'application/json'; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { + 'Content-Type': 'application/json', // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; return this.request({ path: `/pet`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -95,33 +91,27 @@ export class PetApi extends BaseAPI { /** * Deletes a pet */ - deletePet(requestParameters: DeletePetRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling deletePet.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + deletePet = (requestParameters: DeletePetRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'deletePet'); - if (requestParameters.apiKey !== undefined && requestParameters.apiKey !== null) { - headerParameters['api_key'] = String(requestParameters.apiKey); - } - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { + ...(requestParameters.apiKey && { 'api_key': String(requestParameters.apiKey) }), // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; return this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'DELETE', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -129,33 +119,27 @@ export class PetApi extends BaseAPI { * Multiple status values can be provided with comma separated strings * Finds Pets by status */ - findPetsByStatus(requestParameters: FindPetsByStatusRequest): Observable> { - if (requestParameters.status === null || requestParameters.status === undefined) { - throw new RequiredError('status','Required parameter requestParameters.status was null or undefined when calling findPetsByStatus.'); - } - - const queryParameters: HttpQuery = {}; - - if (requestParameters.status) { - queryParameters['status'] = requestParameters.status.join(COLLECTION_FORMATS["csv"]); - } - - const headerParameters: HttpHeaders = {}; + findPetsByStatus = (requestParameters: FindPetsByStatusRequest): Observable> => { + throwIfRequired(requestParameters, 'status', 'findPetsByStatus'); - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + ...(requestParameters.status && { 'status': requestParameters.status.join(COLLECTION_FORMATS['csv']) }), + }; return this.request>({ path: `/pet/findByStatus`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -163,33 +147,27 @@ export class PetApi extends BaseAPI { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags */ - findPetsByTags(requestParameters: FindPetsByTagsRequest): Observable> { - if (requestParameters.tags === null || requestParameters.tags === undefined) { - throw new RequiredError('tags','Required parameter requestParameters.tags was null or undefined when calling findPetsByTags.'); - } - - const queryParameters: HttpQuery = {}; - - if (requestParameters.tags) { - queryParameters['tags'] = requestParameters.tags.join(COLLECTION_FORMATS["csv"]); - } + findPetsByTags = (requestParameters: FindPetsByTagsRequest): Observable> => { + throwIfRequired(requestParameters, 'tags', 'findPetsByTags'); - const headerParameters: HttpHeaders = {}; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + ...(requestParameters.tags && { 'tags': requestParameters.tags.join(COLLECTION_FORMATS['csv']) }), + }; return this.request>({ path: `/pet/findByTags`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -197,55 +175,48 @@ export class PetApi extends BaseAPI { * Returns a single pet * Find pet by ID */ - getPetById(requestParameters: GetPetByIdRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling getPetById.'); - } - - const queryParameters: HttpQuery = {}; + getPetById = (requestParameters: GetPetByIdRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'getPetById'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + ...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication + }; - if (this.configuration && this.configuration.apiKey) { - headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication - } + const query: HttpQuery = { + }; return this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Update an existing pet */ - updatePet(requestParameters: UpdatePetRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updatePet.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + updatePet = (requestParameters: UpdatePetRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'updatePet'); - headerParameters['Content-Type'] = 'application/json'; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { + 'Content-Type': 'application/json', // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; return this.request({ path: `/pet`, method: 'PUT', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -253,23 +224,20 @@ export class PetApi extends BaseAPI { /** * Updates a pet in the store with form data */ - updatePetWithForm(requestParameters: UpdatePetWithFormRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling updatePetWithForm.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + updatePetWithForm = (requestParameters: UpdatePetWithFormRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'updatePetWithForm'); - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; const formData = new FormData(); if (requestParameters.name !== undefined) { @@ -281,10 +249,10 @@ export class PetApi extends BaseAPI { } return this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: formData, }); } @@ -292,23 +260,20 @@ export class PetApi extends BaseAPI { /** * uploads an image */ - uploadFile(requestParameters: UploadFileRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling uploadFile.'); - } + uploadFile = (requestParameters: UploadFileRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'uploadFile'); - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; const formData = new FormData(); if (requestParameters.additionalMetadata !== undefined) { @@ -320,10 +285,10 @@ export class PetApi extends BaseAPI { } return this.request({ - path: `/pet/{petId}/uploadImage`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}/uploadImage`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: formData, }); } @@ -331,9 +296,9 @@ export class PetApi extends BaseAPI { } /** - * @export - * @enum {string} - */ + * @export + * @enum {string} + */ export enum FindPetsByStatusStatusEnum { Available = 'available', Pending = 'pending', diff --git a/samples/client/petstore/typescript-rxjs/builds/default/apis/StoreApi.ts b/samples/client/petstore/typescript-rxjs/builds/default/apis/StoreApi.ts index c0755e5c98f9..d7350a81516d 100644 --- a/samples/client/petstore/typescript-rxjs/builds/default/apis/StoreApi.ts +++ b/samples/client/petstore/typescript-rxjs/builds/default/apis/StoreApi.ts @@ -12,7 +12,7 @@ */ import { Observable } from 'rxjs'; -import { BaseAPI, RequiredError, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; +import { BaseAPI, throwIfRequired, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; import { Order, } from '../models'; @@ -38,20 +38,20 @@ export class StoreApi extends BaseAPI { * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * Delete purchase order by ID */ - deleteOrder(requestParameters: DeleteOrderRequest): Observable { - if (requestParameters.orderId === null || requestParameters.orderId === undefined) { - throw new RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling deleteOrder.'); - } + deleteOrder = (requestParameters: DeleteOrderRequest): Observable => { + throwIfRequired(requestParameters, 'orderId', 'deleteOrder'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + path: `/store/order/{orderId}`.replace(`{orderId}`, encodeURIComponent(String(requestParameters.orderId))), method: 'DELETE', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -59,20 +59,20 @@ export class StoreApi extends BaseAPI { * Returns a map of status codes to quantities * Returns pet inventories by status */ - getInventory(): Observable<{ [key: string]: number; }> { - const queryParameters: HttpQuery = {}; + getInventory = (): Observable<{ [key: string]: number; }> => { - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + ...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication + }; - if (this.configuration && this.configuration.apiKey) { - headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication - } + const query: HttpQuery = { + }; return this.request<{ [key: string]: number; }>({ path: `/store/inventory`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -80,42 +80,41 @@ export class StoreApi extends BaseAPI { * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * Find purchase order by ID */ - getOrderById(requestParameters: GetOrderByIdRequest): Observable { - if (requestParameters.orderId === null || requestParameters.orderId === undefined) { - throw new RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling getOrderById.'); - } + getOrderById = (requestParameters: GetOrderByIdRequest): Observable => { + throwIfRequired(requestParameters, 'orderId', 'getOrderById'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + path: `/store/order/{orderId}`.replace(`{orderId}`, encodeURIComponent(String(requestParameters.orderId))), method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Place an order for a pet */ - placeOrder(requestParameters: PlaceOrderRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling placeOrder.'); - } + placeOrder = (requestParameters: PlaceOrderRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'placeOrder'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - const headerParameters: HttpHeaders = {}; - - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/store/order`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } diff --git a/samples/client/petstore/typescript-rxjs/builds/default/apis/UserApi.ts b/samples/client/petstore/typescript-rxjs/builds/default/apis/UserApi.ts index dee6c06cbea6..8b994caf6c8e 100644 --- a/samples/client/petstore/typescript-rxjs/builds/default/apis/UserApi.ts +++ b/samples/client/petstore/typescript-rxjs/builds/default/apis/UserApi.ts @@ -12,7 +12,7 @@ */ import { Observable } from 'rxjs'; -import { BaseAPI, RequiredError, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; +import { BaseAPI, throwIfRequired, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; import { User, } from '../models'; @@ -56,22 +56,21 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * Create user */ - createUser(requestParameters: CreateUserRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUser.'); - } + createUser = (requestParameters: CreateUserRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'createUser'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - const headerParameters: HttpHeaders = {}; - - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/user`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -79,22 +78,21 @@ export class UserApi extends BaseAPI { /** * Creates list of users with given input array */ - createUsersWithArrayInput(requestParameters: CreateUsersWithArrayInputRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithArrayInput.'); - } - - const queryParameters: HttpQuery = {}; + createUsersWithArrayInput = (requestParameters: CreateUsersWithArrayInputRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'createUsersWithArrayInput'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/user/createWithArray`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -102,22 +100,21 @@ export class UserApi extends BaseAPI { /** * Creates list of users with given input array */ - createUsersWithListInput(requestParameters: CreateUsersWithListInputRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithListInput.'); - } - - const queryParameters: HttpQuery = {}; + createUsersWithListInput = (requestParameters: CreateUsersWithListInputRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'createUsersWithListInput'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/user/createWithList`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -126,88 +123,82 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * Delete user */ - deleteUser(requestParameters: DeleteUserRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling deleteUser.'); - } + deleteUser = (requestParameters: DeleteUserRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'deleteUser'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + path: `/user/{username}`.replace(`{username}`, encodeURIComponent(String(requestParameters.username))), method: 'DELETE', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Get user by user name */ - getUserByName(requestParameters: GetUserByNameRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling getUserByName.'); - } + getUserByName = (requestParameters: GetUserByNameRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'getUserByName'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + path: `/user/{username}`.replace(`{username}`, encodeURIComponent(String(requestParameters.username))), method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Logs user into the system */ - loginUser(requestParameters: LoginUserRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling loginUser.'); - } - - if (requestParameters.password === null || requestParameters.password === undefined) { - throw new RequiredError('password','Required parameter requestParameters.password was null or undefined when calling loginUser.'); - } - - const queryParameters: HttpQuery = {}; + loginUser = (requestParameters: LoginUserRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'loginUser'); + throwIfRequired(requestParameters, 'password', 'loginUser'); - if (requestParameters.username !== undefined && requestParameters.username !== null) { - queryParameters['username'] = requestParameters.username; - } + const headers: HttpHeaders = { + }; - if (requestParameters.password !== undefined && requestParameters.password !== null) { - queryParameters['password'] = requestParameters.password; - } - - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + ...(requestParameters.username && { 'username': requestParameters.username }), + ...(requestParameters.password && { 'password': requestParameters.password }), + }; return this.request({ path: `/user/login`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Logs out current logged in user session */ - logoutUser(): Observable { - const queryParameters: HttpQuery = {}; + logoutUser = (): Observable => { + + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ path: `/user/logout`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -215,26 +206,22 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * Updated user */ - updateUser(requestParameters: UpdateUserRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling updateUser.'); - } - - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updateUser.'); - } - - const queryParameters: HttpQuery = {}; + updateUser = (requestParameters: UpdateUserRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'updateUser'); + throwIfRequired(requestParameters, 'body', 'updateUser'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ - path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + path: `/user/{username}`.replace(`{username}`, encodeURIComponent(String(requestParameters.username))), method: 'PUT', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } diff --git a/samples/client/petstore/typescript-rxjs/builds/default/runtime.ts b/samples/client/petstore/typescript-rxjs/builds/default/runtime.ts index e28e284bf19f..1d160d5d3792 100644 --- a/samples/client/petstore/typescript-rxjs/builds/default/runtime.ts +++ b/samples/client/petstore/typescript-rxjs/builds/default/runtime.ts @@ -66,30 +66,26 @@ 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(this: T, ...middlewares: Middleware[]) { + withMiddleware = (middlewares: Middleware[]) => { const next = this.clone(); - next.middleware = next.middleware.concat(...middlewares); + next.middleware = next.middleware.concat(middlewares); return next; } - withPreMiddleware(this: T, ...preMiddlewares: Array) { - const middlewares = preMiddlewares.map((pre) => ({ pre })); - return this.withMiddleware(...middlewares); - } + withPreMiddleware = (preMiddlewares: Array) => + this.withMiddleware(preMiddlewares.map((pre) => ({ pre }))); - withPostMiddleware(this: T, ...postMiddlewares: Array) { - const middlewares = postMiddlewares.map((post) => ({ post })); - return this.withMiddleware(...middlewares); - } + withPostMiddleware = (postMiddlewares: Array) => + this.withMiddleware(postMiddlewares.map((post) => ({ post }))); - protected request(context: RequestOpts): Observable { - return this.rxjsRequest(this.createRequestArgs(context)).pipe( + protected request = (context: RequestOpts): Observable => + this.rxjsRequest(this.createRequestArgs(context)).pipe( map((res) => { if (res.status >= 200 && res.status < 300) { return res.response as T; @@ -97,15 +93,14 @@ export class BaseAPI { 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 = { @@ -116,9 +111,9 @@ export class BaseAPI { return { url, options }; } - private rxjsRequest(params: RequestContext): Observable { - 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 => { + const preMiddlewares = this.middleware.filter((item) => item.pre); + const postMiddlewares = this.middleware.filter((item) => item.post); return of(params).pipe( map((args) => { @@ -144,19 +139,13 @@ export class BaseAPI { * Create a shallow clone of `this` by constructing a new instance * and then shallow cloning data members. */ - private clone(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 => + 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 = { @@ -186,17 +175,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 +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 {} diff --git a/samples/client/petstore/typescript-rxjs/builds/es6-target/apis/PetApi.ts b/samples/client/petstore/typescript-rxjs/builds/es6-target/apis/PetApi.ts index dab74f1d7bf1..8f8db90ce78a 100644 --- a/samples/client/petstore/typescript-rxjs/builds/es6-target/apis/PetApi.ts +++ b/samples/client/petstore/typescript-rxjs/builds/es6-target/apis/PetApi.ts @@ -12,7 +12,7 @@ */ import { Observable } from 'rxjs'; -import { BaseAPI, RequiredError, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; +import { BaseAPI, throwIfRequired, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; import { ApiResponse, Pet, @@ -63,31 +63,27 @@ export class PetApi extends BaseAPI { /** * Add a new pet to the store */ - addPet(requestParameters: AddPetRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling addPet.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + addPet = (requestParameters: AddPetRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'addPet'); - headerParameters['Content-Type'] = 'application/json'; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { + 'Content-Type': 'application/json', // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; return this.request({ path: `/pet`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -95,33 +91,27 @@ export class PetApi extends BaseAPI { /** * Deletes a pet */ - deletePet(requestParameters: DeletePetRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling deletePet.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + deletePet = (requestParameters: DeletePetRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'deletePet'); - if (requestParameters.apiKey !== undefined && requestParameters.apiKey !== null) { - headerParameters['api_key'] = String(requestParameters.apiKey); - } - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { + ...(requestParameters.apiKey && { 'api_key': String(requestParameters.apiKey) }), // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; return this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'DELETE', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -129,33 +119,27 @@ export class PetApi extends BaseAPI { * Multiple status values can be provided with comma separated strings * Finds Pets by status */ - findPetsByStatus(requestParameters: FindPetsByStatusRequest): Observable> { - if (requestParameters.status === null || requestParameters.status === undefined) { - throw new RequiredError('status','Required parameter requestParameters.status was null or undefined when calling findPetsByStatus.'); - } - - const queryParameters: HttpQuery = {}; - - if (requestParameters.status) { - queryParameters['status'] = requestParameters.status.join(COLLECTION_FORMATS["csv"]); - } - - const headerParameters: HttpHeaders = {}; + findPetsByStatus = (requestParameters: FindPetsByStatusRequest): Observable> => { + throwIfRequired(requestParameters, 'status', 'findPetsByStatus'); - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + ...(requestParameters.status && { 'status': requestParameters.status.join(COLLECTION_FORMATS['csv']) }), + }; return this.request>({ path: `/pet/findByStatus`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -163,33 +147,27 @@ export class PetApi extends BaseAPI { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags */ - findPetsByTags(requestParameters: FindPetsByTagsRequest): Observable> { - if (requestParameters.tags === null || requestParameters.tags === undefined) { - throw new RequiredError('tags','Required parameter requestParameters.tags was null or undefined when calling findPetsByTags.'); - } - - const queryParameters: HttpQuery = {}; - - if (requestParameters.tags) { - queryParameters['tags'] = requestParameters.tags.join(COLLECTION_FORMATS["csv"]); - } + findPetsByTags = (requestParameters: FindPetsByTagsRequest): Observable> => { + throwIfRequired(requestParameters, 'tags', 'findPetsByTags'); - const headerParameters: HttpHeaders = {}; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + ...(requestParameters.tags && { 'tags': requestParameters.tags.join(COLLECTION_FORMATS['csv']) }), + }; return this.request>({ path: `/pet/findByTags`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -197,55 +175,48 @@ export class PetApi extends BaseAPI { * Returns a single pet * Find pet by ID */ - getPetById(requestParameters: GetPetByIdRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling getPetById.'); - } - - const queryParameters: HttpQuery = {}; + getPetById = (requestParameters: GetPetByIdRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'getPetById'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + ...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication + }; - if (this.configuration && this.configuration.apiKey) { - headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication - } + const query: HttpQuery = { + }; return this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Update an existing pet */ - updatePet(requestParameters: UpdatePetRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updatePet.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + updatePet = (requestParameters: UpdatePetRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'updatePet'); - headerParameters['Content-Type'] = 'application/json'; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { + 'Content-Type': 'application/json', // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; return this.request({ path: `/pet`, method: 'PUT', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -253,23 +224,20 @@ export class PetApi extends BaseAPI { /** * Updates a pet in the store with form data */ - updatePetWithForm(requestParameters: UpdatePetWithFormRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling updatePetWithForm.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + updatePetWithForm = (requestParameters: UpdatePetWithFormRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'updatePetWithForm'); - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; const formData = new FormData(); if (requestParameters.name !== undefined) { @@ -281,10 +249,10 @@ export class PetApi extends BaseAPI { } return this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: formData, }); } @@ -292,23 +260,20 @@ export class PetApi extends BaseAPI { /** * uploads an image */ - uploadFile(requestParameters: UploadFileRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling uploadFile.'); - } + uploadFile = (requestParameters: UploadFileRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'uploadFile'); - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; const formData = new FormData(); if (requestParameters.additionalMetadata !== undefined) { @@ -320,10 +285,10 @@ export class PetApi extends BaseAPI { } return this.request({ - path: `/pet/{petId}/uploadImage`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}/uploadImage`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: formData, }); } @@ -331,9 +296,9 @@ export class PetApi extends BaseAPI { } /** - * @export - * @enum {string} - */ + * @export + * @enum {string} + */ export enum FindPetsByStatusStatusEnum { Available = 'available', Pending = 'pending', diff --git a/samples/client/petstore/typescript-rxjs/builds/es6-target/apis/StoreApi.ts b/samples/client/petstore/typescript-rxjs/builds/es6-target/apis/StoreApi.ts index c0755e5c98f9..d7350a81516d 100644 --- a/samples/client/petstore/typescript-rxjs/builds/es6-target/apis/StoreApi.ts +++ b/samples/client/petstore/typescript-rxjs/builds/es6-target/apis/StoreApi.ts @@ -12,7 +12,7 @@ */ import { Observable } from 'rxjs'; -import { BaseAPI, RequiredError, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; +import { BaseAPI, throwIfRequired, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; import { Order, } from '../models'; @@ -38,20 +38,20 @@ export class StoreApi extends BaseAPI { * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * Delete purchase order by ID */ - deleteOrder(requestParameters: DeleteOrderRequest): Observable { - if (requestParameters.orderId === null || requestParameters.orderId === undefined) { - throw new RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling deleteOrder.'); - } + deleteOrder = (requestParameters: DeleteOrderRequest): Observable => { + throwIfRequired(requestParameters, 'orderId', 'deleteOrder'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + path: `/store/order/{orderId}`.replace(`{orderId}`, encodeURIComponent(String(requestParameters.orderId))), method: 'DELETE', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -59,20 +59,20 @@ export class StoreApi extends BaseAPI { * Returns a map of status codes to quantities * Returns pet inventories by status */ - getInventory(): Observable<{ [key: string]: number; }> { - const queryParameters: HttpQuery = {}; + getInventory = (): Observable<{ [key: string]: number; }> => { - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + ...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication + }; - if (this.configuration && this.configuration.apiKey) { - headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication - } + const query: HttpQuery = { + }; return this.request<{ [key: string]: number; }>({ path: `/store/inventory`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -80,42 +80,41 @@ export class StoreApi extends BaseAPI { * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * Find purchase order by ID */ - getOrderById(requestParameters: GetOrderByIdRequest): Observable { - if (requestParameters.orderId === null || requestParameters.orderId === undefined) { - throw new RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling getOrderById.'); - } + getOrderById = (requestParameters: GetOrderByIdRequest): Observable => { + throwIfRequired(requestParameters, 'orderId', 'getOrderById'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + path: `/store/order/{orderId}`.replace(`{orderId}`, encodeURIComponent(String(requestParameters.orderId))), method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Place an order for a pet */ - placeOrder(requestParameters: PlaceOrderRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling placeOrder.'); - } + placeOrder = (requestParameters: PlaceOrderRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'placeOrder'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - const headerParameters: HttpHeaders = {}; - - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/store/order`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } diff --git a/samples/client/petstore/typescript-rxjs/builds/es6-target/apis/UserApi.ts b/samples/client/petstore/typescript-rxjs/builds/es6-target/apis/UserApi.ts index dee6c06cbea6..8b994caf6c8e 100644 --- a/samples/client/petstore/typescript-rxjs/builds/es6-target/apis/UserApi.ts +++ b/samples/client/petstore/typescript-rxjs/builds/es6-target/apis/UserApi.ts @@ -12,7 +12,7 @@ */ import { Observable } from 'rxjs'; -import { BaseAPI, RequiredError, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; +import { BaseAPI, throwIfRequired, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; import { User, } from '../models'; @@ -56,22 +56,21 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * Create user */ - createUser(requestParameters: CreateUserRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUser.'); - } + createUser = (requestParameters: CreateUserRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'createUser'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - const headerParameters: HttpHeaders = {}; - - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/user`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -79,22 +78,21 @@ export class UserApi extends BaseAPI { /** * Creates list of users with given input array */ - createUsersWithArrayInput(requestParameters: CreateUsersWithArrayInputRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithArrayInput.'); - } - - const queryParameters: HttpQuery = {}; + createUsersWithArrayInput = (requestParameters: CreateUsersWithArrayInputRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'createUsersWithArrayInput'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/user/createWithArray`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -102,22 +100,21 @@ export class UserApi extends BaseAPI { /** * Creates list of users with given input array */ - createUsersWithListInput(requestParameters: CreateUsersWithListInputRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithListInput.'); - } - - const queryParameters: HttpQuery = {}; + createUsersWithListInput = (requestParameters: CreateUsersWithListInputRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'createUsersWithListInput'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/user/createWithList`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -126,88 +123,82 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * Delete user */ - deleteUser(requestParameters: DeleteUserRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling deleteUser.'); - } + deleteUser = (requestParameters: DeleteUserRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'deleteUser'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + path: `/user/{username}`.replace(`{username}`, encodeURIComponent(String(requestParameters.username))), method: 'DELETE', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Get user by user name */ - getUserByName(requestParameters: GetUserByNameRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling getUserByName.'); - } + getUserByName = (requestParameters: GetUserByNameRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'getUserByName'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + path: `/user/{username}`.replace(`{username}`, encodeURIComponent(String(requestParameters.username))), method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Logs user into the system */ - loginUser(requestParameters: LoginUserRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling loginUser.'); - } - - if (requestParameters.password === null || requestParameters.password === undefined) { - throw new RequiredError('password','Required parameter requestParameters.password was null or undefined when calling loginUser.'); - } - - const queryParameters: HttpQuery = {}; + loginUser = (requestParameters: LoginUserRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'loginUser'); + throwIfRequired(requestParameters, 'password', 'loginUser'); - if (requestParameters.username !== undefined && requestParameters.username !== null) { - queryParameters['username'] = requestParameters.username; - } + const headers: HttpHeaders = { + }; - if (requestParameters.password !== undefined && requestParameters.password !== null) { - queryParameters['password'] = requestParameters.password; - } - - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + ...(requestParameters.username && { 'username': requestParameters.username }), + ...(requestParameters.password && { 'password': requestParameters.password }), + }; return this.request({ path: `/user/login`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Logs out current logged in user session */ - logoutUser(): Observable { - const queryParameters: HttpQuery = {}; + logoutUser = (): Observable => { + + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ path: `/user/logout`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -215,26 +206,22 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * Updated user */ - updateUser(requestParameters: UpdateUserRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling updateUser.'); - } - - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updateUser.'); - } - - const queryParameters: HttpQuery = {}; + updateUser = (requestParameters: UpdateUserRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'updateUser'); + throwIfRequired(requestParameters, 'body', 'updateUser'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ - path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + path: `/user/{username}`.replace(`{username}`, encodeURIComponent(String(requestParameters.username))), method: 'PUT', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } diff --git a/samples/client/petstore/typescript-rxjs/builds/es6-target/runtime.ts b/samples/client/petstore/typescript-rxjs/builds/es6-target/runtime.ts index e28e284bf19f..1d160d5d3792 100644 --- a/samples/client/petstore/typescript-rxjs/builds/es6-target/runtime.ts +++ b/samples/client/petstore/typescript-rxjs/builds/es6-target/runtime.ts @@ -66,30 +66,26 @@ 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(this: T, ...middlewares: Middleware[]) { + withMiddleware = (middlewares: Middleware[]) => { const next = this.clone(); - next.middleware = next.middleware.concat(...middlewares); + next.middleware = next.middleware.concat(middlewares); return next; } - withPreMiddleware(this: T, ...preMiddlewares: Array) { - const middlewares = preMiddlewares.map((pre) => ({ pre })); - return this.withMiddleware(...middlewares); - } + withPreMiddleware = (preMiddlewares: Array) => + this.withMiddleware(preMiddlewares.map((pre) => ({ pre }))); - withPostMiddleware(this: T, ...postMiddlewares: Array) { - const middlewares = postMiddlewares.map((post) => ({ post })); - return this.withMiddleware(...middlewares); - } + withPostMiddleware = (postMiddlewares: Array) => + this.withMiddleware(postMiddlewares.map((post) => ({ post }))); - protected request(context: RequestOpts): Observable { - return this.rxjsRequest(this.createRequestArgs(context)).pipe( + protected request = (context: RequestOpts): Observable => + this.rxjsRequest(this.createRequestArgs(context)).pipe( map((res) => { if (res.status >= 200 && res.status < 300) { return res.response as T; @@ -97,15 +93,14 @@ export class BaseAPI { 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 = { @@ -116,9 +111,9 @@ export class BaseAPI { return { url, options }; } - private rxjsRequest(params: RequestContext): Observable { - 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 => { + const preMiddlewares = this.middleware.filter((item) => item.pre); + const postMiddlewares = this.middleware.filter((item) => item.post); return of(params).pipe( map((args) => { @@ -144,19 +139,13 @@ export class BaseAPI { * Create a shallow clone of `this` by constructing a new instance * and then shallow cloning data members. */ - private clone(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 => + 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 = { @@ -186,17 +175,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 +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 {} diff --git a/samples/client/petstore/typescript-rxjs/builds/with-interfaces/apis/PetApi.ts b/samples/client/petstore/typescript-rxjs/builds/with-interfaces/apis/PetApi.ts index dab74f1d7bf1..8f8db90ce78a 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-interfaces/apis/PetApi.ts +++ b/samples/client/petstore/typescript-rxjs/builds/with-interfaces/apis/PetApi.ts @@ -12,7 +12,7 @@ */ import { Observable } from 'rxjs'; -import { BaseAPI, RequiredError, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; +import { BaseAPI, throwIfRequired, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; import { ApiResponse, Pet, @@ -63,31 +63,27 @@ export class PetApi extends BaseAPI { /** * Add a new pet to the store */ - addPet(requestParameters: AddPetRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling addPet.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + addPet = (requestParameters: AddPetRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'addPet'); - headerParameters['Content-Type'] = 'application/json'; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { + 'Content-Type': 'application/json', // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; return this.request({ path: `/pet`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -95,33 +91,27 @@ export class PetApi extends BaseAPI { /** * Deletes a pet */ - deletePet(requestParameters: DeletePetRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling deletePet.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + deletePet = (requestParameters: DeletePetRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'deletePet'); - if (requestParameters.apiKey !== undefined && requestParameters.apiKey !== null) { - headerParameters['api_key'] = String(requestParameters.apiKey); - } - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { + ...(requestParameters.apiKey && { 'api_key': String(requestParameters.apiKey) }), // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; return this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'DELETE', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -129,33 +119,27 @@ export class PetApi extends BaseAPI { * Multiple status values can be provided with comma separated strings * Finds Pets by status */ - findPetsByStatus(requestParameters: FindPetsByStatusRequest): Observable> { - if (requestParameters.status === null || requestParameters.status === undefined) { - throw new RequiredError('status','Required parameter requestParameters.status was null or undefined when calling findPetsByStatus.'); - } - - const queryParameters: HttpQuery = {}; - - if (requestParameters.status) { - queryParameters['status'] = requestParameters.status.join(COLLECTION_FORMATS["csv"]); - } - - const headerParameters: HttpHeaders = {}; + findPetsByStatus = (requestParameters: FindPetsByStatusRequest): Observable> => { + throwIfRequired(requestParameters, 'status', 'findPetsByStatus'); - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + ...(requestParameters.status && { 'status': requestParameters.status.join(COLLECTION_FORMATS['csv']) }), + }; return this.request>({ path: `/pet/findByStatus`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -163,33 +147,27 @@ export class PetApi extends BaseAPI { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags */ - findPetsByTags(requestParameters: FindPetsByTagsRequest): Observable> { - if (requestParameters.tags === null || requestParameters.tags === undefined) { - throw new RequiredError('tags','Required parameter requestParameters.tags was null or undefined when calling findPetsByTags.'); - } - - const queryParameters: HttpQuery = {}; - - if (requestParameters.tags) { - queryParameters['tags'] = requestParameters.tags.join(COLLECTION_FORMATS["csv"]); - } + findPetsByTags = (requestParameters: FindPetsByTagsRequest): Observable> => { + throwIfRequired(requestParameters, 'tags', 'findPetsByTags'); - const headerParameters: HttpHeaders = {}; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + ...(requestParameters.tags && { 'tags': requestParameters.tags.join(COLLECTION_FORMATS['csv']) }), + }; return this.request>({ path: `/pet/findByTags`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -197,55 +175,48 @@ export class PetApi extends BaseAPI { * Returns a single pet * Find pet by ID */ - getPetById(requestParameters: GetPetByIdRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling getPetById.'); - } - - const queryParameters: HttpQuery = {}; + getPetById = (requestParameters: GetPetByIdRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'getPetById'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + ...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication + }; - if (this.configuration && this.configuration.apiKey) { - headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication - } + const query: HttpQuery = { + }; return this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Update an existing pet */ - updatePet(requestParameters: UpdatePetRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updatePet.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + updatePet = (requestParameters: UpdatePetRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'updatePet'); - headerParameters['Content-Type'] = 'application/json'; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { + 'Content-Type': 'application/json', // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; return this.request({ path: `/pet`, method: 'PUT', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -253,23 +224,20 @@ export class PetApi extends BaseAPI { /** * Updates a pet in the store with form data */ - updatePetWithForm(requestParameters: UpdatePetWithFormRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling updatePetWithForm.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + updatePetWithForm = (requestParameters: UpdatePetWithFormRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'updatePetWithForm'); - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; const formData = new FormData(); if (requestParameters.name !== undefined) { @@ -281,10 +249,10 @@ export class PetApi extends BaseAPI { } return this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: formData, }); } @@ -292,23 +260,20 @@ export class PetApi extends BaseAPI { /** * uploads an image */ - uploadFile(requestParameters: UploadFileRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling uploadFile.'); - } + uploadFile = (requestParameters: UploadFileRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'uploadFile'); - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; const formData = new FormData(); if (requestParameters.additionalMetadata !== undefined) { @@ -320,10 +285,10 @@ export class PetApi extends BaseAPI { } return this.request({ - path: `/pet/{petId}/uploadImage`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}/uploadImage`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: formData, }); } @@ -331,9 +296,9 @@ export class PetApi extends BaseAPI { } /** - * @export - * @enum {string} - */ + * @export + * @enum {string} + */ export enum FindPetsByStatusStatusEnum { Available = 'available', Pending = 'pending', diff --git a/samples/client/petstore/typescript-rxjs/builds/with-interfaces/apis/StoreApi.ts b/samples/client/petstore/typescript-rxjs/builds/with-interfaces/apis/StoreApi.ts index c0755e5c98f9..d7350a81516d 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-interfaces/apis/StoreApi.ts +++ b/samples/client/petstore/typescript-rxjs/builds/with-interfaces/apis/StoreApi.ts @@ -12,7 +12,7 @@ */ import { Observable } from 'rxjs'; -import { BaseAPI, RequiredError, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; +import { BaseAPI, throwIfRequired, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; import { Order, } from '../models'; @@ -38,20 +38,20 @@ export class StoreApi extends BaseAPI { * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * Delete purchase order by ID */ - deleteOrder(requestParameters: DeleteOrderRequest): Observable { - if (requestParameters.orderId === null || requestParameters.orderId === undefined) { - throw new RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling deleteOrder.'); - } + deleteOrder = (requestParameters: DeleteOrderRequest): Observable => { + throwIfRequired(requestParameters, 'orderId', 'deleteOrder'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + path: `/store/order/{orderId}`.replace(`{orderId}`, encodeURIComponent(String(requestParameters.orderId))), method: 'DELETE', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -59,20 +59,20 @@ export class StoreApi extends BaseAPI { * Returns a map of status codes to quantities * Returns pet inventories by status */ - getInventory(): Observable<{ [key: string]: number; }> { - const queryParameters: HttpQuery = {}; + getInventory = (): Observable<{ [key: string]: number; }> => { - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + ...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication + }; - if (this.configuration && this.configuration.apiKey) { - headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication - } + const query: HttpQuery = { + }; return this.request<{ [key: string]: number; }>({ path: `/store/inventory`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -80,42 +80,41 @@ export class StoreApi extends BaseAPI { * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * Find purchase order by ID */ - getOrderById(requestParameters: GetOrderByIdRequest): Observable { - if (requestParameters.orderId === null || requestParameters.orderId === undefined) { - throw new RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling getOrderById.'); - } + getOrderById = (requestParameters: GetOrderByIdRequest): Observable => { + throwIfRequired(requestParameters, 'orderId', 'getOrderById'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + path: `/store/order/{orderId}`.replace(`{orderId}`, encodeURIComponent(String(requestParameters.orderId))), method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Place an order for a pet */ - placeOrder(requestParameters: PlaceOrderRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling placeOrder.'); - } + placeOrder = (requestParameters: PlaceOrderRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'placeOrder'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - const headerParameters: HttpHeaders = {}; - - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/store/order`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } diff --git a/samples/client/petstore/typescript-rxjs/builds/with-interfaces/apis/UserApi.ts b/samples/client/petstore/typescript-rxjs/builds/with-interfaces/apis/UserApi.ts index dee6c06cbea6..8b994caf6c8e 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-interfaces/apis/UserApi.ts +++ b/samples/client/petstore/typescript-rxjs/builds/with-interfaces/apis/UserApi.ts @@ -12,7 +12,7 @@ */ import { Observable } from 'rxjs'; -import { BaseAPI, RequiredError, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; +import { BaseAPI, throwIfRequired, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; import { User, } from '../models'; @@ -56,22 +56,21 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * Create user */ - createUser(requestParameters: CreateUserRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUser.'); - } + createUser = (requestParameters: CreateUserRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'createUser'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - const headerParameters: HttpHeaders = {}; - - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/user`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -79,22 +78,21 @@ export class UserApi extends BaseAPI { /** * Creates list of users with given input array */ - createUsersWithArrayInput(requestParameters: CreateUsersWithArrayInputRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithArrayInput.'); - } - - const queryParameters: HttpQuery = {}; + createUsersWithArrayInput = (requestParameters: CreateUsersWithArrayInputRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'createUsersWithArrayInput'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/user/createWithArray`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -102,22 +100,21 @@ export class UserApi extends BaseAPI { /** * Creates list of users with given input array */ - createUsersWithListInput(requestParameters: CreateUsersWithListInputRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithListInput.'); - } - - const queryParameters: HttpQuery = {}; + createUsersWithListInput = (requestParameters: CreateUsersWithListInputRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'createUsersWithListInput'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/user/createWithList`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -126,88 +123,82 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * Delete user */ - deleteUser(requestParameters: DeleteUserRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling deleteUser.'); - } + deleteUser = (requestParameters: DeleteUserRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'deleteUser'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + path: `/user/{username}`.replace(`{username}`, encodeURIComponent(String(requestParameters.username))), method: 'DELETE', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Get user by user name */ - getUserByName(requestParameters: GetUserByNameRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling getUserByName.'); - } + getUserByName = (requestParameters: GetUserByNameRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'getUserByName'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + path: `/user/{username}`.replace(`{username}`, encodeURIComponent(String(requestParameters.username))), method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Logs user into the system */ - loginUser(requestParameters: LoginUserRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling loginUser.'); - } - - if (requestParameters.password === null || requestParameters.password === undefined) { - throw new RequiredError('password','Required parameter requestParameters.password was null or undefined when calling loginUser.'); - } - - const queryParameters: HttpQuery = {}; + loginUser = (requestParameters: LoginUserRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'loginUser'); + throwIfRequired(requestParameters, 'password', 'loginUser'); - if (requestParameters.username !== undefined && requestParameters.username !== null) { - queryParameters['username'] = requestParameters.username; - } + const headers: HttpHeaders = { + }; - if (requestParameters.password !== undefined && requestParameters.password !== null) { - queryParameters['password'] = requestParameters.password; - } - - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + ...(requestParameters.username && { 'username': requestParameters.username }), + ...(requestParameters.password && { 'password': requestParameters.password }), + }; return this.request({ path: `/user/login`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Logs out current logged in user session */ - logoutUser(): Observable { - const queryParameters: HttpQuery = {}; + logoutUser = (): Observable => { + + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ path: `/user/logout`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -215,26 +206,22 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * Updated user */ - updateUser(requestParameters: UpdateUserRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling updateUser.'); - } - - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updateUser.'); - } - - const queryParameters: HttpQuery = {}; + updateUser = (requestParameters: UpdateUserRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'updateUser'); + throwIfRequired(requestParameters, 'body', 'updateUser'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ - path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + path: `/user/{username}`.replace(`{username}`, encodeURIComponent(String(requestParameters.username))), method: 'PUT', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } diff --git a/samples/client/petstore/typescript-rxjs/builds/with-interfaces/runtime.ts b/samples/client/petstore/typescript-rxjs/builds/with-interfaces/runtime.ts index e28e284bf19f..1d160d5d3792 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-interfaces/runtime.ts +++ b/samples/client/petstore/typescript-rxjs/builds/with-interfaces/runtime.ts @@ -66,30 +66,26 @@ 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(this: T, ...middlewares: Middleware[]) { + withMiddleware = (middlewares: Middleware[]) => { const next = this.clone(); - next.middleware = next.middleware.concat(...middlewares); + next.middleware = next.middleware.concat(middlewares); return next; } - withPreMiddleware(this: T, ...preMiddlewares: Array) { - const middlewares = preMiddlewares.map((pre) => ({ pre })); - return this.withMiddleware(...middlewares); - } + withPreMiddleware = (preMiddlewares: Array) => + this.withMiddleware(preMiddlewares.map((pre) => ({ pre }))); - withPostMiddleware(this: T, ...postMiddlewares: Array) { - const middlewares = postMiddlewares.map((post) => ({ post })); - return this.withMiddleware(...middlewares); - } + withPostMiddleware = (postMiddlewares: Array) => + this.withMiddleware(postMiddlewares.map((post) => ({ post }))); - protected request(context: RequestOpts): Observable { - return this.rxjsRequest(this.createRequestArgs(context)).pipe( + protected request = (context: RequestOpts): Observable => + this.rxjsRequest(this.createRequestArgs(context)).pipe( map((res) => { if (res.status >= 200 && res.status < 300) { return res.response as T; @@ -97,15 +93,14 @@ export class BaseAPI { 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 = { @@ -116,9 +111,9 @@ export class BaseAPI { return { url, options }; } - private rxjsRequest(params: RequestContext): Observable { - 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 => { + const preMiddlewares = this.middleware.filter((item) => item.pre); + const postMiddlewares = this.middleware.filter((item) => item.post); return of(params).pipe( map((args) => { @@ -144,19 +139,13 @@ export class BaseAPI { * Create a shallow clone of `this` by constructing a new instance * and then shallow cloning data members. */ - private clone(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 => + 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 = { @@ -186,17 +175,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 +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 {} diff --git a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/apis/PetApi.ts b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/apis/PetApi.ts index dab74f1d7bf1..8f8db90ce78a 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/apis/PetApi.ts +++ b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/apis/PetApi.ts @@ -12,7 +12,7 @@ */ import { Observable } from 'rxjs'; -import { BaseAPI, RequiredError, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; +import { BaseAPI, throwIfRequired, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; import { ApiResponse, Pet, @@ -63,31 +63,27 @@ export class PetApi extends BaseAPI { /** * Add a new pet to the store */ - addPet(requestParameters: AddPetRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling addPet.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + addPet = (requestParameters: AddPetRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'addPet'); - headerParameters['Content-Type'] = 'application/json'; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { + 'Content-Type': 'application/json', // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; return this.request({ path: `/pet`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -95,33 +91,27 @@ export class PetApi extends BaseAPI { /** * Deletes a pet */ - deletePet(requestParameters: DeletePetRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling deletePet.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + deletePet = (requestParameters: DeletePetRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'deletePet'); - if (requestParameters.apiKey !== undefined && requestParameters.apiKey !== null) { - headerParameters['api_key'] = String(requestParameters.apiKey); - } - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { + ...(requestParameters.apiKey && { 'api_key': String(requestParameters.apiKey) }), // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; return this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'DELETE', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -129,33 +119,27 @@ export class PetApi extends BaseAPI { * Multiple status values can be provided with comma separated strings * Finds Pets by status */ - findPetsByStatus(requestParameters: FindPetsByStatusRequest): Observable> { - if (requestParameters.status === null || requestParameters.status === undefined) { - throw new RequiredError('status','Required parameter requestParameters.status was null or undefined when calling findPetsByStatus.'); - } - - const queryParameters: HttpQuery = {}; - - if (requestParameters.status) { - queryParameters['status'] = requestParameters.status.join(COLLECTION_FORMATS["csv"]); - } - - const headerParameters: HttpHeaders = {}; + findPetsByStatus = (requestParameters: FindPetsByStatusRequest): Observable> => { + throwIfRequired(requestParameters, 'status', 'findPetsByStatus'); - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + ...(requestParameters.status && { 'status': requestParameters.status.join(COLLECTION_FORMATS['csv']) }), + }; return this.request>({ path: `/pet/findByStatus`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -163,33 +147,27 @@ export class PetApi extends BaseAPI { * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags */ - findPetsByTags(requestParameters: FindPetsByTagsRequest): Observable> { - if (requestParameters.tags === null || requestParameters.tags === undefined) { - throw new RequiredError('tags','Required parameter requestParameters.tags was null or undefined when calling findPetsByTags.'); - } - - const queryParameters: HttpQuery = {}; - - if (requestParameters.tags) { - queryParameters['tags'] = requestParameters.tags.join(COLLECTION_FORMATS["csv"]); - } + findPetsByTags = (requestParameters: FindPetsByTagsRequest): Observable> => { + throwIfRequired(requestParameters, 'tags', 'findPetsByTags'); - const headerParameters: HttpHeaders = {}; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + ...(requestParameters.tags && { 'tags': requestParameters.tags.join(COLLECTION_FORMATS['csv']) }), + }; return this.request>({ path: `/pet/findByTags`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -197,55 +175,48 @@ export class PetApi extends BaseAPI { * Returns a single pet * Find pet by ID */ - getPetById(requestParameters: GetPetByIdRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling getPetById.'); - } - - const queryParameters: HttpQuery = {}; + getPetById = (requestParameters: GetPetByIdRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'getPetById'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + ...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication + }; - if (this.configuration && this.configuration.apiKey) { - headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication - } + const query: HttpQuery = { + }; return this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Update an existing pet */ - updatePet(requestParameters: UpdatePetRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updatePet.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + updatePet = (requestParameters: UpdatePetRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'updatePet'); - headerParameters['Content-Type'] = 'application/json'; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { + 'Content-Type': 'application/json', // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; return this.request({ path: `/pet`, method: 'PUT', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -253,23 +224,20 @@ export class PetApi extends BaseAPI { /** * Updates a pet in the store with form data */ - updatePetWithForm(requestParameters: UpdatePetWithFormRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling updatePetWithForm.'); - } - - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; + updatePetWithForm = (requestParameters: UpdatePetWithFormRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'updatePetWithForm'); - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; const formData = new FormData(); if (requestParameters.name !== undefined) { @@ -281,10 +249,10 @@ export class PetApi extends BaseAPI { } return this.request({ - path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: formData, }); } @@ -292,23 +260,20 @@ export class PetApi extends BaseAPI { /** * uploads an image */ - uploadFile(requestParameters: UploadFileRequest): Observable { - if (requestParameters.petId === null || requestParameters.petId === undefined) { - throw new RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling uploadFile.'); - } + uploadFile = (requestParameters: UploadFileRequest): Observable => { + throwIfRequired(requestParameters, 'petId', 'uploadFile'); - const queryParameters: HttpQuery = {}; - - const headerParameters: HttpHeaders = {}; - - if (this.configuration && this.configuration.accessToken) { + const headers: HttpHeaders = { // oauth required - if (typeof this.configuration.accessToken === 'function') { - headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); - } else { - headerParameters["Authorization"] = this.configuration.accessToken; - } - } + ...(this.configuration.accessToken && { + Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' + ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) + : this.configuration.accessToken) + }), + }; + + const query: HttpQuery = { + }; const formData = new FormData(); if (requestParameters.additionalMetadata !== undefined) { @@ -320,10 +285,10 @@ export class PetApi extends BaseAPI { } return this.request({ - path: `/pet/{petId}/uploadImage`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + path: `/pet/{petId}/uploadImage`.replace(`{petId}`, encodeURIComponent(String(requestParameters.petId))), method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: formData, }); } @@ -331,9 +296,9 @@ export class PetApi extends BaseAPI { } /** - * @export - * @enum {string} - */ + * @export + * @enum {string} + */ export enum FindPetsByStatusStatusEnum { Available = 'available', Pending = 'pending', diff --git a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/apis/StoreApi.ts b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/apis/StoreApi.ts index c0755e5c98f9..d7350a81516d 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/apis/StoreApi.ts +++ b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/apis/StoreApi.ts @@ -12,7 +12,7 @@ */ import { Observable } from 'rxjs'; -import { BaseAPI, RequiredError, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; +import { BaseAPI, throwIfRequired, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; import { Order, } from '../models'; @@ -38,20 +38,20 @@ export class StoreApi extends BaseAPI { * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * Delete purchase order by ID */ - deleteOrder(requestParameters: DeleteOrderRequest): Observable { - if (requestParameters.orderId === null || requestParameters.orderId === undefined) { - throw new RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling deleteOrder.'); - } + deleteOrder = (requestParameters: DeleteOrderRequest): Observable => { + throwIfRequired(requestParameters, 'orderId', 'deleteOrder'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + path: `/store/order/{orderId}`.replace(`{orderId}`, encodeURIComponent(String(requestParameters.orderId))), method: 'DELETE', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -59,20 +59,20 @@ export class StoreApi extends BaseAPI { * Returns a map of status codes to quantities * Returns pet inventories by status */ - getInventory(): Observable<{ [key: string]: number; }> { - const queryParameters: HttpQuery = {}; + getInventory = (): Observable<{ [key: string]: number; }> => { - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + ...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication + }; - if (this.configuration && this.configuration.apiKey) { - headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication - } + const query: HttpQuery = { + }; return this.request<{ [key: string]: number; }>({ path: `/store/inventory`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -80,42 +80,41 @@ export class StoreApi extends BaseAPI { * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * Find purchase order by ID */ - getOrderById(requestParameters: GetOrderByIdRequest): Observable { - if (requestParameters.orderId === null || requestParameters.orderId === undefined) { - throw new RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling getOrderById.'); - } + getOrderById = (requestParameters: GetOrderByIdRequest): Observable => { + throwIfRequired(requestParameters, 'orderId', 'getOrderById'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + path: `/store/order/{orderId}`.replace(`{orderId}`, encodeURIComponent(String(requestParameters.orderId))), method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Place an order for a pet */ - placeOrder(requestParameters: PlaceOrderRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling placeOrder.'); - } + placeOrder = (requestParameters: PlaceOrderRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'placeOrder'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - const headerParameters: HttpHeaders = {}; - - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/store/order`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } diff --git a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/apis/UserApi.ts b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/apis/UserApi.ts index dee6c06cbea6..8b994caf6c8e 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/apis/UserApi.ts +++ b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/apis/UserApi.ts @@ -12,7 +12,7 @@ */ import { Observable } from 'rxjs'; -import { BaseAPI, RequiredError, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; +import { BaseAPI, throwIfRequired, HttpHeaders, HttpQuery, COLLECTION_FORMATS } from '../runtime'; import { User, } from '../models'; @@ -56,22 +56,21 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * Create user */ - createUser(requestParameters: CreateUserRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUser.'); - } + createUser = (requestParameters: CreateUserRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'createUser'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - const headerParameters: HttpHeaders = {}; - - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/user`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -79,22 +78,21 @@ export class UserApi extends BaseAPI { /** * Creates list of users with given input array */ - createUsersWithArrayInput(requestParameters: CreateUsersWithArrayInputRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithArrayInput.'); - } - - const queryParameters: HttpQuery = {}; + createUsersWithArrayInput = (requestParameters: CreateUsersWithArrayInputRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'createUsersWithArrayInput'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/user/createWithArray`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -102,22 +100,21 @@ export class UserApi extends BaseAPI { /** * Creates list of users with given input array */ - createUsersWithListInput(requestParameters: CreateUsersWithListInputRequest): Observable { - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithListInput.'); - } - - const queryParameters: HttpQuery = {}; + createUsersWithListInput = (requestParameters: CreateUsersWithListInputRequest): Observable => { + throwIfRequired(requestParameters, 'body', 'createUsersWithListInput'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ path: `/user/createWithList`, method: 'POST', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } @@ -126,88 +123,82 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * Delete user */ - deleteUser(requestParameters: DeleteUserRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling deleteUser.'); - } + deleteUser = (requestParameters: DeleteUserRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'deleteUser'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + path: `/user/{username}`.replace(`{username}`, encodeURIComponent(String(requestParameters.username))), method: 'DELETE', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Get user by user name */ - getUserByName(requestParameters: GetUserByNameRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling getUserByName.'); - } + getUserByName = (requestParameters: GetUserByNameRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'getUserByName'); - const queryParameters: HttpQuery = {}; + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ - path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + path: `/user/{username}`.replace(`{username}`, encodeURIComponent(String(requestParameters.username))), method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Logs user into the system */ - loginUser(requestParameters: LoginUserRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling loginUser.'); - } - - if (requestParameters.password === null || requestParameters.password === undefined) { - throw new RequiredError('password','Required parameter requestParameters.password was null or undefined when calling loginUser.'); - } - - const queryParameters: HttpQuery = {}; + loginUser = (requestParameters: LoginUserRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'loginUser'); + throwIfRequired(requestParameters, 'password', 'loginUser'); - if (requestParameters.username !== undefined && requestParameters.username !== null) { - queryParameters['username'] = requestParameters.username; - } + const headers: HttpHeaders = { + }; - if (requestParameters.password !== undefined && requestParameters.password !== null) { - queryParameters['password'] = requestParameters.password; - } - - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + ...(requestParameters.username && { 'username': requestParameters.username }), + ...(requestParameters.password && { 'password': requestParameters.password }), + }; return this.request({ path: `/user/login`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } /** * Logs out current logged in user session */ - logoutUser(): Observable { - const queryParameters: HttpQuery = {}; + logoutUser = (): Observable => { + + const headers: HttpHeaders = { + }; - const headerParameters: HttpHeaders = {}; + const query: HttpQuery = { + }; return this.request({ path: `/user/logout`, method: 'GET', - headers: headerParameters, - query: queryParameters, + headers, + query, }); } @@ -215,26 +206,22 @@ export class UserApi extends BaseAPI { * This can only be done by the logged in user. * Updated user */ - updateUser(requestParameters: UpdateUserRequest): Observable { - if (requestParameters.username === null || requestParameters.username === undefined) { - throw new RequiredError('username','Required parameter requestParameters.username was null or undefined when calling updateUser.'); - } - - if (requestParameters.body === null || requestParameters.body === undefined) { - throw new RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updateUser.'); - } - - const queryParameters: HttpQuery = {}; + updateUser = (requestParameters: UpdateUserRequest): Observable => { + throwIfRequired(requestParameters, 'username', 'updateUser'); + throwIfRequired(requestParameters, 'body', 'updateUser'); - const headerParameters: HttpHeaders = {}; + const headers: HttpHeaders = { + 'Content-Type': 'application/json', + }; - headerParameters['Content-Type'] = 'application/json'; + const query: HttpQuery = { + }; return this.request({ - path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + path: `/user/{username}`.replace(`{username}`, encodeURIComponent(String(requestParameters.username))), method: 'PUT', - headers: headerParameters, - query: queryParameters, + headers, + query, body: requestParameters.body, }); } diff --git a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/runtime.ts b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/runtime.ts index e28e284bf19f..1d160d5d3792 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/runtime.ts +++ b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/runtime.ts @@ -66,30 +66,26 @@ 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(this: T, ...middlewares: Middleware[]) { + withMiddleware = (middlewares: Middleware[]) => { const next = this.clone(); - next.middleware = next.middleware.concat(...middlewares); + next.middleware = next.middleware.concat(middlewares); return next; } - withPreMiddleware(this: T, ...preMiddlewares: Array) { - const middlewares = preMiddlewares.map((pre) => ({ pre })); - return this.withMiddleware(...middlewares); - } + withPreMiddleware = (preMiddlewares: Array) => + this.withMiddleware(preMiddlewares.map((pre) => ({ pre }))); - withPostMiddleware(this: T, ...postMiddlewares: Array) { - const middlewares = postMiddlewares.map((post) => ({ post })); - return this.withMiddleware(...middlewares); - } + withPostMiddleware = (postMiddlewares: Array) => + this.withMiddleware(postMiddlewares.map((post) => ({ post }))); - protected request(context: RequestOpts): Observable { - return this.rxjsRequest(this.createRequestArgs(context)).pipe( + protected request = (context: RequestOpts): Observable => + this.rxjsRequest(this.createRequestArgs(context)).pipe( map((res) => { if (res.status >= 200 && res.status < 300) { return res.response as T; @@ -97,15 +93,14 @@ export class BaseAPI { 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 = { @@ -116,9 +111,9 @@ export class BaseAPI { return { url, options }; } - private rxjsRequest(params: RequestContext): Observable { - 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 => { + const preMiddlewares = this.middleware.filter((item) => item.pre); + const postMiddlewares = this.middleware.filter((item) => item.post); return of(params).pipe( map((args) => { @@ -144,19 +139,13 @@ export class BaseAPI { * Create a shallow clone of `this` by constructing a new instance * and then shallow cloning data members. */ - private clone(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 => + 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 = { @@ -186,17 +175,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 +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 {}