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

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

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

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

* feat(typescript-rxjs): regenerate samples

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

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

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

* feat(typescript-rxjs): regenerate samples

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

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

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

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

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

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

* refactor(typescript-rxjs): remove unused ModelPropertyNaming

* feat(typescript-rxjs): regenerate samples

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

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

View File

@ -67,10 +67,8 @@ sidebar_label: typescript-rxjs
<li>HttpMethod</li> <li>HttpMethod</li>
<li>HttpQuery</li> <li>HttpQuery</li>
<li>Middleware</li> <li>Middleware</li>
<li>ModelPropertyNaming</li>
<li>RequestArgs</li> <li>RequestArgs</li>
<li>RequestOpts</li> <li>RequestOpts</li>
<li>RequiredError</li>
<li>ResponseArgs</li> <li>ResponseArgs</li>
<li>abstract</li> <li>abstract</li>
<li>await</li> <li>await</li>
@ -90,7 +88,6 @@ sidebar_label: typescript-rxjs
<li>double</li> <li>double</li>
<li>else</li> <li>else</li>
<li>enum</li> <li>enum</li>
<li>exists</li>
<li>export</li> <li>export</li>
<li>extends</li> <li>extends</li>
<li>false</li> <li>false</li>

View File

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

View File

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

View File

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

View File

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

View File

@ -12,7 +12,7 @@
*/ */
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { BaseAPI, HttpHeaders, HttpQuery, throwIfRequired, encodeURI, COLLECTION_FORMATS } from '../runtime'; import { BaseAPI, HttpHeaders, HttpQuery, throwIfNullOrUndefined, encodeURI, COLLECTION_FORMATS } from '../runtime';
import { import {
ApiResponse, ApiResponse,
Pet, Pet,
@ -63,45 +63,47 @@ export class PetApi extends BaseAPI {
/** /**
* Add a new pet to the store * Add a new pet to the store
*/ */
addPet = (requestParameters: AddPetRequest): Observable<void> => { addPet = ({ body }: AddPetRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'addPet'); throwIfNullOrUndefined(body, 'addPet');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
return this.request<void>({ return this.request<void>({
path: '/pet', path: '/pet',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Deletes a pet * Deletes a pet
*/ */
deletePet = (requestParameters: DeletePetRequest): Observable<void> => { deletePet = ({ petId, apiKey }: DeletePetRequest): Observable<void> => {
throwIfRequired(requestParameters, 'petId', 'deletePet'); throwIfNullOrUndefined(petId, 'deletePet');
const headers: HttpHeaders = { const headers: HttpHeaders = {
...(requestParameters.apiKey && { 'api_key': String(requestParameters.apiKey) }), ...(apiKey != null ? { 'api_key': String(apiKey) } : undefined),
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
return this.request<void>({ return this.request<void>({
path: '/pet/{petId}'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}'.replace('{petId}', encodeURI(petId)),
method: 'DELETE', method: 'DELETE',
headers, headers,
}); });
@ -111,20 +113,21 @@ export class PetApi extends BaseAPI {
* Multiple status values can be provided with comma separated strings * Multiple status values can be provided with comma separated strings
* Finds Pets by status * Finds Pets by status
*/ */
findPetsByStatus = (requestParameters: FindPetsByStatusRequest): Observable<Array<Pet>> => { findPetsByStatus = ({ status }: FindPetsByStatusRequest): Observable<Array<Pet>> => {
throwIfRequired(requestParameters, 'status', 'findPetsByStatus'); throwIfNullOrUndefined(status, 'findPetsByStatus');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const query: HttpQuery = { const query: HttpQuery = { // required parameters are used directly since they are already checked by throwIfNullOrUndefined
...(requestParameters.status && { 'status': requestParameters.status.join(COLLECTION_FORMATS['csv']) }), 'status': status.join(COLLECTION_FORMATS['csv']),
}; };
return this.request<Array<Pet>>({ return this.request<Array<Pet>>({
@ -139,20 +142,21 @@ export class PetApi extends BaseAPI {
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* Finds Pets by tags * Finds Pets by tags
*/ */
findPetsByTags = (requestParameters: FindPetsByTagsRequest): Observable<Array<Pet>> => { findPetsByTags = ({ tags }: FindPetsByTagsRequest): Observable<Array<Pet>> => {
throwIfRequired(requestParameters, 'tags', 'findPetsByTags'); throwIfNullOrUndefined(tags, 'findPetsByTags');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const query: HttpQuery = { const query: HttpQuery = { // required parameters are used directly since they are already checked by throwIfNullOrUndefined
...(requestParameters.tags && { 'tags': requestParameters.tags.join(COLLECTION_FORMATS['csv']) }), 'tags': tags.join(COLLECTION_FORMATS['csv']),
}; };
return this.request<Array<Pet>>({ return this.request<Array<Pet>>({
@ -167,15 +171,15 @@ export class PetApi extends BaseAPI {
* Returns a single pet * Returns a single pet
* Find pet by ID * Find pet by ID
*/ */
getPetById = (requestParameters: GetPetByIdRequest): Observable<Pet> => { getPetById = ({ petId }: GetPetByIdRequest): Observable<Pet> => {
throwIfRequired(requestParameters, 'petId', 'getPetById'); throwIfNullOrUndefined(petId, 'getPetById');
const headers: HttpHeaders = { const headers: HttpHeaders = {
...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication ...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication
}; };
return this.request<Pet>({ return this.request<Pet>({
path: '/pet/{petId}'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}'.replace('{petId}', encodeURI(petId)),
method: 'GET', method: 'GET',
headers, headers,
}); });
@ -184,53 +188,50 @@ export class PetApi extends BaseAPI {
/** /**
* Update an existing pet * Update an existing pet
*/ */
updatePet = (requestParameters: UpdatePetRequest): Observable<void> => { updatePet = ({ body }: UpdatePetRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'updatePet'); throwIfNullOrUndefined(body, 'updatePet');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
return this.request<void>({ return this.request<void>({
path: '/pet', path: '/pet',
method: 'PUT', method: 'PUT',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Updates a pet in the store with form data * Updates a pet in the store with form data
*/ */
updatePetWithForm = (requestParameters: UpdatePetWithFormRequest): Observable<void> => { updatePetWithForm = ({ petId, name, status }: UpdatePetWithFormRequest): Observable<void> => {
throwIfRequired(requestParameters, 'petId', 'updatePetWithForm'); throwIfNullOrUndefined(petId, 'updatePetWithForm');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const formData = new FormData(); const formData = new FormData();
if (requestParameters.name !== undefined) { if (name !== undefined) { formData.append('name', name as any); }
formData.append('name', requestParameters.name as any); if (status !== undefined) { formData.append('status', status as any); }
}
if (requestParameters.status !== undefined) {
formData.append('status', requestParameters.status as any);
}
return this.request<void>({ return this.request<void>({
path: '/pet/{petId}'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}'.replace('{petId}', encodeURI(petId)),
method: 'POST', method: 'POST',
headers, headers,
body: formData, body: formData,
@ -240,29 +241,25 @@ export class PetApi extends BaseAPI {
/** /**
* uploads an image * uploads an image
*/ */
uploadFile = (requestParameters: UploadFileRequest): Observable<ApiResponse> => { uploadFile = ({ petId, additionalMetadata, file }: UploadFileRequest): Observable<ApiResponse> => {
throwIfRequired(requestParameters, 'petId', 'uploadFile'); throwIfNullOrUndefined(petId, 'uploadFile');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const formData = new FormData(); const formData = new FormData();
if (requestParameters.additionalMetadata !== undefined) { if (additionalMetadata !== undefined) { formData.append('additionalMetadata', additionalMetadata as any); }
formData.append('additionalMetadata', requestParameters.additionalMetadata as any); if (file !== undefined) { formData.append('file', file as any); }
}
if (requestParameters.file !== undefined) {
formData.append('file', requestParameters.file as any);
}
return this.request<ApiResponse>({ return this.request<ApiResponse>({
path: '/pet/{petId}/uploadImage'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}/uploadImage'.replace('{petId}', encodeURI(petId)),
method: 'POST', method: 'POST',
headers, headers,
body: formData, body: formData,

View File

@ -12,7 +12,7 @@
*/ */
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { BaseAPI, HttpHeaders, throwIfRequired, encodeURI } from '../runtime'; import { BaseAPI, HttpHeaders, throwIfNullOrUndefined, encodeURI } from '../runtime';
import { import {
Order, Order,
} from '../models'; } from '../models';
@ -38,11 +38,11 @@ export class StoreApi extends BaseAPI {
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* Delete purchase order by ID * Delete purchase order by ID
*/ */
deleteOrder = (requestParameters: DeleteOrderRequest): Observable<void> => { deleteOrder = ({ orderId }: DeleteOrderRequest): Observable<void> => {
throwIfRequired(requestParameters, 'orderId', 'deleteOrder'); throwIfNullOrUndefined(orderId, 'deleteOrder');
return this.request<void>({ return this.request<void>({
path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(requestParameters.orderId)), path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(orderId)),
method: 'DELETE', method: 'DELETE',
}); });
}; };
@ -67,11 +67,11 @@ export class StoreApi extends BaseAPI {
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* Find purchase order by ID * Find purchase order by ID
*/ */
getOrderById = (requestParameters: GetOrderByIdRequest): Observable<Order> => { getOrderById = ({ orderId }: GetOrderByIdRequest): Observable<Order> => {
throwIfRequired(requestParameters, 'orderId', 'getOrderById'); throwIfNullOrUndefined(orderId, 'getOrderById');
return this.request<Order>({ return this.request<Order>({
path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(requestParameters.orderId)), path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(orderId)),
method: 'GET', method: 'GET',
}); });
}; };
@ -79,8 +79,8 @@ export class StoreApi extends BaseAPI {
/** /**
* Place an order for a pet * Place an order for a pet
*/ */
placeOrder = (requestParameters: PlaceOrderRequest): Observable<Order> => { placeOrder = ({ body }: PlaceOrderRequest): Observable<Order> => {
throwIfRequired(requestParameters, 'body', 'placeOrder'); throwIfNullOrUndefined(body, 'placeOrder');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -90,7 +90,7 @@ export class StoreApi extends BaseAPI {
path: '/store/order', path: '/store/order',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };

View File

@ -12,7 +12,7 @@
*/ */
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { BaseAPI, HttpHeaders, HttpQuery, throwIfRequired, encodeURI } from '../runtime'; import { BaseAPI, HttpHeaders, HttpQuery, throwIfNullOrUndefined, encodeURI } from '../runtime';
import { import {
User, User,
} from '../models'; } from '../models';
@ -56,8 +56,8 @@ export class UserApi extends BaseAPI {
* This can only be done by the logged in user. * This can only be done by the logged in user.
* Create user * Create user
*/ */
createUser = (requestParameters: CreateUserRequest): Observable<void> => { createUser = ({ body }: CreateUserRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'createUser'); throwIfNullOrUndefined(body, 'createUser');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -67,15 +67,15 @@ export class UserApi extends BaseAPI {
path: '/user', path: '/user',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Creates list of users with given input array * Creates list of users with given input array
*/ */
createUsersWithArrayInput = (requestParameters: CreateUsersWithArrayInputRequest): Observable<void> => { createUsersWithArrayInput = ({ body }: CreateUsersWithArrayInputRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'createUsersWithArrayInput'); throwIfNullOrUndefined(body, 'createUsersWithArrayInput');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -85,15 +85,15 @@ export class UserApi extends BaseAPI {
path: '/user/createWithArray', path: '/user/createWithArray',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Creates list of users with given input array * Creates list of users with given input array
*/ */
createUsersWithListInput = (requestParameters: CreateUsersWithListInputRequest): Observable<void> => { createUsersWithListInput = ({ body }: CreateUsersWithListInputRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'createUsersWithListInput'); throwIfNullOrUndefined(body, 'createUsersWithListInput');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -103,7 +103,7 @@ export class UserApi extends BaseAPI {
path: '/user/createWithList', path: '/user/createWithList',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
@ -111,11 +111,11 @@ export class UserApi extends BaseAPI {
* This can only be done by the logged in user. * This can only be done by the logged in user.
* Delete user * Delete user
*/ */
deleteUser = (requestParameters: DeleteUserRequest): Observable<void> => { deleteUser = ({ username }: DeleteUserRequest): Observable<void> => {
throwIfRequired(requestParameters, 'username', 'deleteUser'); throwIfNullOrUndefined(username, 'deleteUser');
return this.request<void>({ return this.request<void>({
path: '/user/{username}'.replace('{username}', encodeURI(requestParameters.username)), path: '/user/{username}'.replace('{username}', encodeURI(username)),
method: 'DELETE', method: 'DELETE',
}); });
}; };
@ -123,11 +123,11 @@ export class UserApi extends BaseAPI {
/** /**
* Get user by user name * Get user by user name
*/ */
getUserByName = (requestParameters: GetUserByNameRequest): Observable<User> => { getUserByName = ({ username }: GetUserByNameRequest): Observable<User> => {
throwIfRequired(requestParameters, 'username', 'getUserByName'); throwIfNullOrUndefined(username, 'getUserByName');
return this.request<User>({ return this.request<User>({
path: '/user/{username}'.replace('{username}', encodeURI(requestParameters.username)), path: '/user/{username}'.replace('{username}', encodeURI(username)),
method: 'GET', method: 'GET',
}); });
}; };
@ -135,13 +135,13 @@ export class UserApi extends BaseAPI {
/** /**
* Logs user into the system * Logs user into the system
*/ */
loginUser = (requestParameters: LoginUserRequest): Observable<string> => { loginUser = ({ username, password }: LoginUserRequest): Observable<string> => {
throwIfRequired(requestParameters, 'username', 'loginUser'); throwIfNullOrUndefined(username, 'loginUser');
throwIfRequired(requestParameters, 'password', 'loginUser'); throwIfNullOrUndefined(password, 'loginUser');
const query: HttpQuery = { const query: HttpQuery = { // required parameters are used directly since they are already checked by throwIfNullOrUndefined
...(requestParameters.username && { 'username': requestParameters.username }), 'username': username,
...(requestParameters.password && { 'password': requestParameters.password }), 'password': password,
}; };
return this.request<string>({ return this.request<string>({
@ -165,19 +165,19 @@ export class UserApi extends BaseAPI {
* This can only be done by the logged in user. * This can only be done by the logged in user.
* Updated user * Updated user
*/ */
updateUser = (requestParameters: UpdateUserRequest): Observable<void> => { updateUser = ({ username, body }: UpdateUserRequest): Observable<void> => {
throwIfRequired(requestParameters, 'username', 'updateUser'); throwIfNullOrUndefined(username, 'updateUser');
throwIfRequired(requestParameters, 'body', 'updateUser'); throwIfNullOrUndefined(body, 'updateUser');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}; };
return this.request<void>({ return this.request<void>({
path: '/user/{username}'.replace('{username}', encodeURI(requestParameters.username)), path: '/user/{username}'.replace('{username}', encodeURI(username)),
method: 'PUT', method: 'PUT',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };

View File

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

View File

@ -12,7 +12,7 @@
*/ */
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { BaseAPI, HttpHeaders, HttpQuery, throwIfRequired, encodeURI, COLLECTION_FORMATS } from '../runtime'; import { BaseAPI, HttpHeaders, HttpQuery, throwIfNullOrUndefined, encodeURI, COLLECTION_FORMATS } from '../runtime';
import { import {
ApiResponse, ApiResponse,
Pet, Pet,
@ -63,45 +63,47 @@ export class PetApi extends BaseAPI {
/** /**
* Add a new pet to the store * Add a new pet to the store
*/ */
addPet = (requestParameters: AddPetRequest): Observable<void> => { addPet = ({ body }: AddPetRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'addPet'); throwIfNullOrUndefined(body, 'addPet');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
return this.request<void>({ return this.request<void>({
path: '/pet', path: '/pet',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Deletes a pet * Deletes a pet
*/ */
deletePet = (requestParameters: DeletePetRequest): Observable<void> => { deletePet = ({ petId, apiKey }: DeletePetRequest): Observable<void> => {
throwIfRequired(requestParameters, 'petId', 'deletePet'); throwIfNullOrUndefined(petId, 'deletePet');
const headers: HttpHeaders = { const headers: HttpHeaders = {
...(requestParameters.apiKey && { 'api_key': String(requestParameters.apiKey) }), ...(apiKey != null ? { 'api_key': String(apiKey) } : undefined),
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
return this.request<void>({ return this.request<void>({
path: '/pet/{petId}'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}'.replace('{petId}', encodeURI(petId)),
method: 'DELETE', method: 'DELETE',
headers, headers,
}); });
@ -111,20 +113,21 @@ export class PetApi extends BaseAPI {
* Multiple status values can be provided with comma separated strings * Multiple status values can be provided with comma separated strings
* Finds Pets by status * Finds Pets by status
*/ */
findPetsByStatus = (requestParameters: FindPetsByStatusRequest): Observable<Array<Pet>> => { findPetsByStatus = ({ status }: FindPetsByStatusRequest): Observable<Array<Pet>> => {
throwIfRequired(requestParameters, 'status', 'findPetsByStatus'); throwIfNullOrUndefined(status, 'findPetsByStatus');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const query: HttpQuery = { const query: HttpQuery = { // required parameters are used directly since they are already checked by throwIfNullOrUndefined
...(requestParameters.status && { 'status': requestParameters.status.join(COLLECTION_FORMATS['csv']) }), 'status': status.join(COLLECTION_FORMATS['csv']),
}; };
return this.request<Array<Pet>>({ return this.request<Array<Pet>>({
@ -139,20 +142,21 @@ export class PetApi extends BaseAPI {
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* Finds Pets by tags * Finds Pets by tags
*/ */
findPetsByTags = (requestParameters: FindPetsByTagsRequest): Observable<Array<Pet>> => { findPetsByTags = ({ tags }: FindPetsByTagsRequest): Observable<Array<Pet>> => {
throwIfRequired(requestParameters, 'tags', 'findPetsByTags'); throwIfNullOrUndefined(tags, 'findPetsByTags');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const query: HttpQuery = { const query: HttpQuery = { // required parameters are used directly since they are already checked by throwIfNullOrUndefined
...(requestParameters.tags && { 'tags': requestParameters.tags.join(COLLECTION_FORMATS['csv']) }), 'tags': tags.join(COLLECTION_FORMATS['csv']),
}; };
return this.request<Array<Pet>>({ return this.request<Array<Pet>>({
@ -167,15 +171,15 @@ export class PetApi extends BaseAPI {
* Returns a single pet * Returns a single pet
* Find pet by ID * Find pet by ID
*/ */
getPetById = (requestParameters: GetPetByIdRequest): Observable<Pet> => { getPetById = ({ petId }: GetPetByIdRequest): Observable<Pet> => {
throwIfRequired(requestParameters, 'petId', 'getPetById'); throwIfNullOrUndefined(petId, 'getPetById');
const headers: HttpHeaders = { const headers: HttpHeaders = {
...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication ...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication
}; };
return this.request<Pet>({ return this.request<Pet>({
path: '/pet/{petId}'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}'.replace('{petId}', encodeURI(petId)),
method: 'GET', method: 'GET',
headers, headers,
}); });
@ -184,53 +188,50 @@ export class PetApi extends BaseAPI {
/** /**
* Update an existing pet * Update an existing pet
*/ */
updatePet = (requestParameters: UpdatePetRequest): Observable<void> => { updatePet = ({ body }: UpdatePetRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'updatePet'); throwIfNullOrUndefined(body, 'updatePet');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
return this.request<void>({ return this.request<void>({
path: '/pet', path: '/pet',
method: 'PUT', method: 'PUT',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Updates a pet in the store with form data * Updates a pet in the store with form data
*/ */
updatePetWithForm = (requestParameters: UpdatePetWithFormRequest): Observable<void> => { updatePetWithForm = ({ petId, name, status }: UpdatePetWithFormRequest): Observable<void> => {
throwIfRequired(requestParameters, 'petId', 'updatePetWithForm'); throwIfNullOrUndefined(petId, 'updatePetWithForm');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const formData = new FormData(); const formData = new FormData();
if (requestParameters.name !== undefined) { if (name !== undefined) { formData.append('name', name as any); }
formData.append('name', requestParameters.name as any); if (status !== undefined) { formData.append('status', status as any); }
}
if (requestParameters.status !== undefined) {
formData.append('status', requestParameters.status as any);
}
return this.request<void>({ return this.request<void>({
path: '/pet/{petId}'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}'.replace('{petId}', encodeURI(petId)),
method: 'POST', method: 'POST',
headers, headers,
body: formData, body: formData,
@ -240,29 +241,25 @@ export class PetApi extends BaseAPI {
/** /**
* uploads an image * uploads an image
*/ */
uploadFile = (requestParameters: UploadFileRequest): Observable<ApiResponse> => { uploadFile = ({ petId, additionalMetadata, file }: UploadFileRequest): Observable<ApiResponse> => {
throwIfRequired(requestParameters, 'petId', 'uploadFile'); throwIfNullOrUndefined(petId, 'uploadFile');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const formData = new FormData(); const formData = new FormData();
if (requestParameters.additionalMetadata !== undefined) { if (additionalMetadata !== undefined) { formData.append('additionalMetadata', additionalMetadata as any); }
formData.append('additionalMetadata', requestParameters.additionalMetadata as any); if (file !== undefined) { formData.append('file', file as any); }
}
if (requestParameters.file !== undefined) {
formData.append('file', requestParameters.file as any);
}
return this.request<ApiResponse>({ return this.request<ApiResponse>({
path: '/pet/{petId}/uploadImage'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}/uploadImage'.replace('{petId}', encodeURI(petId)),
method: 'POST', method: 'POST',
headers, headers,
body: formData, body: formData,

View File

@ -12,7 +12,7 @@
*/ */
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { BaseAPI, HttpHeaders, throwIfRequired, encodeURI } from '../runtime'; import { BaseAPI, HttpHeaders, throwIfNullOrUndefined, encodeURI } from '../runtime';
import { import {
Order, Order,
} from '../models'; } from '../models';
@ -38,11 +38,11 @@ export class StoreApi extends BaseAPI {
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* Delete purchase order by ID * Delete purchase order by ID
*/ */
deleteOrder = (requestParameters: DeleteOrderRequest): Observable<void> => { deleteOrder = ({ orderId }: DeleteOrderRequest): Observable<void> => {
throwIfRequired(requestParameters, 'orderId', 'deleteOrder'); throwIfNullOrUndefined(orderId, 'deleteOrder');
return this.request<void>({ return this.request<void>({
path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(requestParameters.orderId)), path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(orderId)),
method: 'DELETE', method: 'DELETE',
}); });
}; };
@ -67,11 +67,11 @@ export class StoreApi extends BaseAPI {
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* Find purchase order by ID * Find purchase order by ID
*/ */
getOrderById = (requestParameters: GetOrderByIdRequest): Observable<Order> => { getOrderById = ({ orderId }: GetOrderByIdRequest): Observable<Order> => {
throwIfRequired(requestParameters, 'orderId', 'getOrderById'); throwIfNullOrUndefined(orderId, 'getOrderById');
return this.request<Order>({ return this.request<Order>({
path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(requestParameters.orderId)), path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(orderId)),
method: 'GET', method: 'GET',
}); });
}; };
@ -79,8 +79,8 @@ export class StoreApi extends BaseAPI {
/** /**
* Place an order for a pet * Place an order for a pet
*/ */
placeOrder = (requestParameters: PlaceOrderRequest): Observable<Order> => { placeOrder = ({ body }: PlaceOrderRequest): Observable<Order> => {
throwIfRequired(requestParameters, 'body', 'placeOrder'); throwIfNullOrUndefined(body, 'placeOrder');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -90,7 +90,7 @@ export class StoreApi extends BaseAPI {
path: '/store/order', path: '/store/order',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };

View File

@ -12,7 +12,7 @@
*/ */
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { BaseAPI, HttpHeaders, HttpQuery, throwIfRequired, encodeURI } from '../runtime'; import { BaseAPI, HttpHeaders, HttpQuery, throwIfNullOrUndefined, encodeURI } from '../runtime';
import { import {
User, User,
} from '../models'; } from '../models';
@ -56,8 +56,8 @@ export class UserApi extends BaseAPI {
* This can only be done by the logged in user. * This can only be done by the logged in user.
* Create user * Create user
*/ */
createUser = (requestParameters: CreateUserRequest): Observable<void> => { createUser = ({ body }: CreateUserRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'createUser'); throwIfNullOrUndefined(body, 'createUser');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -67,15 +67,15 @@ export class UserApi extends BaseAPI {
path: '/user', path: '/user',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Creates list of users with given input array * Creates list of users with given input array
*/ */
createUsersWithArrayInput = (requestParameters: CreateUsersWithArrayInputRequest): Observable<void> => { createUsersWithArrayInput = ({ body }: CreateUsersWithArrayInputRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'createUsersWithArrayInput'); throwIfNullOrUndefined(body, 'createUsersWithArrayInput');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -85,15 +85,15 @@ export class UserApi extends BaseAPI {
path: '/user/createWithArray', path: '/user/createWithArray',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Creates list of users with given input array * Creates list of users with given input array
*/ */
createUsersWithListInput = (requestParameters: CreateUsersWithListInputRequest): Observable<void> => { createUsersWithListInput = ({ body }: CreateUsersWithListInputRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'createUsersWithListInput'); throwIfNullOrUndefined(body, 'createUsersWithListInput');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -103,7 +103,7 @@ export class UserApi extends BaseAPI {
path: '/user/createWithList', path: '/user/createWithList',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
@ -111,11 +111,11 @@ export class UserApi extends BaseAPI {
* This can only be done by the logged in user. * This can only be done by the logged in user.
* Delete user * Delete user
*/ */
deleteUser = (requestParameters: DeleteUserRequest): Observable<void> => { deleteUser = ({ username }: DeleteUserRequest): Observable<void> => {
throwIfRequired(requestParameters, 'username', 'deleteUser'); throwIfNullOrUndefined(username, 'deleteUser');
return this.request<void>({ return this.request<void>({
path: '/user/{username}'.replace('{username}', encodeURI(requestParameters.username)), path: '/user/{username}'.replace('{username}', encodeURI(username)),
method: 'DELETE', method: 'DELETE',
}); });
}; };
@ -123,11 +123,11 @@ export class UserApi extends BaseAPI {
/** /**
* Get user by user name * Get user by user name
*/ */
getUserByName = (requestParameters: GetUserByNameRequest): Observable<User> => { getUserByName = ({ username }: GetUserByNameRequest): Observable<User> => {
throwIfRequired(requestParameters, 'username', 'getUserByName'); throwIfNullOrUndefined(username, 'getUserByName');
return this.request<User>({ return this.request<User>({
path: '/user/{username}'.replace('{username}', encodeURI(requestParameters.username)), path: '/user/{username}'.replace('{username}', encodeURI(username)),
method: 'GET', method: 'GET',
}); });
}; };
@ -135,13 +135,13 @@ export class UserApi extends BaseAPI {
/** /**
* Logs user into the system * Logs user into the system
*/ */
loginUser = (requestParameters: LoginUserRequest): Observable<string> => { loginUser = ({ username, password }: LoginUserRequest): Observable<string> => {
throwIfRequired(requestParameters, 'username', 'loginUser'); throwIfNullOrUndefined(username, 'loginUser');
throwIfRequired(requestParameters, 'password', 'loginUser'); throwIfNullOrUndefined(password, 'loginUser');
const query: HttpQuery = { const query: HttpQuery = { // required parameters are used directly since they are already checked by throwIfNullOrUndefined
...(requestParameters.username && { 'username': requestParameters.username }), 'username': username,
...(requestParameters.password && { 'password': requestParameters.password }), 'password': password,
}; };
return this.request<string>({ return this.request<string>({
@ -165,19 +165,19 @@ export class UserApi extends BaseAPI {
* This can only be done by the logged in user. * This can only be done by the logged in user.
* Updated user * Updated user
*/ */
updateUser = (requestParameters: UpdateUserRequest): Observable<void> => { updateUser = ({ username, body }: UpdateUserRequest): Observable<void> => {
throwIfRequired(requestParameters, 'username', 'updateUser'); throwIfNullOrUndefined(username, 'updateUser');
throwIfRequired(requestParameters, 'body', 'updateUser'); throwIfNullOrUndefined(body, 'updateUser');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}; };
return this.request<void>({ return this.request<void>({
path: '/user/{username}'.replace('{username}', encodeURI(requestParameters.username)), path: '/user/{username}'.replace('{username}', encodeURI(username)),
method: 'PUT', method: 'PUT',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };

View File

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

View File

@ -12,7 +12,7 @@
*/ */
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { BaseAPI, HttpHeaders, HttpQuery, throwIfRequired, encodeURI, COLLECTION_FORMATS } from '../runtime'; import { BaseAPI, HttpHeaders, HttpQuery, throwIfNullOrUndefined, encodeURI, COLLECTION_FORMATS } from '../runtime';
import { import {
ApiResponse, ApiResponse,
Pet, Pet,
@ -63,45 +63,47 @@ export class PetApi extends BaseAPI {
/** /**
* Add a new pet to the store * Add a new pet to the store
*/ */
addPet = (requestParameters: AddPetRequest): Observable<void> => { addPet = ({ body }: AddPetRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'addPet'); throwIfNullOrUndefined(body, 'addPet');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
return this.request<void>({ return this.request<void>({
path: '/pet', path: '/pet',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Deletes a pet * Deletes a pet
*/ */
deletePet = (requestParameters: DeletePetRequest): Observable<void> => { deletePet = ({ petId, apiKey }: DeletePetRequest): Observable<void> => {
throwIfRequired(requestParameters, 'petId', 'deletePet'); throwIfNullOrUndefined(petId, 'deletePet');
const headers: HttpHeaders = { const headers: HttpHeaders = {
...(requestParameters.apiKey && { 'api_key': String(requestParameters.apiKey) }), ...(apiKey != null ? { 'api_key': String(apiKey) } : undefined),
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
return this.request<void>({ return this.request<void>({
path: '/pet/{petId}'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}'.replace('{petId}', encodeURI(petId)),
method: 'DELETE', method: 'DELETE',
headers, headers,
}); });
@ -111,20 +113,21 @@ export class PetApi extends BaseAPI {
* Multiple status values can be provided with comma separated strings * Multiple status values can be provided with comma separated strings
* Finds Pets by status * Finds Pets by status
*/ */
findPetsByStatus = (requestParameters: FindPetsByStatusRequest): Observable<Array<Pet>> => { findPetsByStatus = ({ status }: FindPetsByStatusRequest): Observable<Array<Pet>> => {
throwIfRequired(requestParameters, 'status', 'findPetsByStatus'); throwIfNullOrUndefined(status, 'findPetsByStatus');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const query: HttpQuery = { const query: HttpQuery = { // required parameters are used directly since they are already checked by throwIfNullOrUndefined
...(requestParameters.status && { 'status': requestParameters.status.join(COLLECTION_FORMATS['csv']) }), 'status': status.join(COLLECTION_FORMATS['csv']),
}; };
return this.request<Array<Pet>>({ return this.request<Array<Pet>>({
@ -139,20 +142,21 @@ export class PetApi extends BaseAPI {
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* Finds Pets by tags * Finds Pets by tags
*/ */
findPetsByTags = (requestParameters: FindPetsByTagsRequest): Observable<Array<Pet>> => { findPetsByTags = ({ tags }: FindPetsByTagsRequest): Observable<Array<Pet>> => {
throwIfRequired(requestParameters, 'tags', 'findPetsByTags'); throwIfNullOrUndefined(tags, 'findPetsByTags');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const query: HttpQuery = { const query: HttpQuery = { // required parameters are used directly since they are already checked by throwIfNullOrUndefined
...(requestParameters.tags && { 'tags': requestParameters.tags.join(COLLECTION_FORMATS['csv']) }), 'tags': tags.join(COLLECTION_FORMATS['csv']),
}; };
return this.request<Array<Pet>>({ return this.request<Array<Pet>>({
@ -167,15 +171,15 @@ export class PetApi extends BaseAPI {
* Returns a single pet * Returns a single pet
* Find pet by ID * Find pet by ID
*/ */
getPetById = (requestParameters: GetPetByIdRequest): Observable<Pet> => { getPetById = ({ petId }: GetPetByIdRequest): Observable<Pet> => {
throwIfRequired(requestParameters, 'petId', 'getPetById'); throwIfNullOrUndefined(petId, 'getPetById');
const headers: HttpHeaders = { const headers: HttpHeaders = {
...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication ...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication
}; };
return this.request<Pet>({ return this.request<Pet>({
path: '/pet/{petId}'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}'.replace('{petId}', encodeURI(petId)),
method: 'GET', method: 'GET',
headers, headers,
}); });
@ -184,53 +188,50 @@ export class PetApi extends BaseAPI {
/** /**
* Update an existing pet * Update an existing pet
*/ */
updatePet = (requestParameters: UpdatePetRequest): Observable<void> => { updatePet = ({ body }: UpdatePetRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'updatePet'); throwIfNullOrUndefined(body, 'updatePet');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
return this.request<void>({ return this.request<void>({
path: '/pet', path: '/pet',
method: 'PUT', method: 'PUT',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Updates a pet in the store with form data * Updates a pet in the store with form data
*/ */
updatePetWithForm = (requestParameters: UpdatePetWithFormRequest): Observable<void> => { updatePetWithForm = ({ petId, name, status }: UpdatePetWithFormRequest): Observable<void> => {
throwIfRequired(requestParameters, 'petId', 'updatePetWithForm'); throwIfNullOrUndefined(petId, 'updatePetWithForm');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const formData = new FormData(); const formData = new FormData();
if (requestParameters.name !== undefined) { if (name !== undefined) { formData.append('name', name as any); }
formData.append('name', requestParameters.name as any); if (status !== undefined) { formData.append('status', status as any); }
}
if (requestParameters.status !== undefined) {
formData.append('status', requestParameters.status as any);
}
return this.request<void>({ return this.request<void>({
path: '/pet/{petId}'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}'.replace('{petId}', encodeURI(petId)),
method: 'POST', method: 'POST',
headers, headers,
body: formData, body: formData,
@ -240,29 +241,25 @@ export class PetApi extends BaseAPI {
/** /**
* uploads an image * uploads an image
*/ */
uploadFile = (requestParameters: UploadFileRequest): Observable<ApiResponse> => { uploadFile = ({ petId, additionalMetadata, file }: UploadFileRequest): Observable<ApiResponse> => {
throwIfRequired(requestParameters, 'petId', 'uploadFile'); throwIfNullOrUndefined(petId, 'uploadFile');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const formData = new FormData(); const formData = new FormData();
if (requestParameters.additionalMetadata !== undefined) { if (additionalMetadata !== undefined) { formData.append('additionalMetadata', additionalMetadata as any); }
formData.append('additionalMetadata', requestParameters.additionalMetadata as any); if (file !== undefined) { formData.append('file', file as any); }
}
if (requestParameters.file !== undefined) {
formData.append('file', requestParameters.file as any);
}
return this.request<ApiResponse>({ return this.request<ApiResponse>({
path: '/pet/{petId}/uploadImage'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}/uploadImage'.replace('{petId}', encodeURI(petId)),
method: 'POST', method: 'POST',
headers, headers,
body: formData, body: formData,

View File

@ -12,7 +12,7 @@
*/ */
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { BaseAPI, HttpHeaders, throwIfRequired, encodeURI } from '../runtime'; import { BaseAPI, HttpHeaders, throwIfNullOrUndefined, encodeURI } from '../runtime';
import { import {
Order, Order,
} from '../models'; } from '../models';
@ -38,11 +38,11 @@ export class StoreApi extends BaseAPI {
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* Delete purchase order by ID * Delete purchase order by ID
*/ */
deleteOrder = (requestParameters: DeleteOrderRequest): Observable<void> => { deleteOrder = ({ orderId }: DeleteOrderRequest): Observable<void> => {
throwIfRequired(requestParameters, 'orderId', 'deleteOrder'); throwIfNullOrUndefined(orderId, 'deleteOrder');
return this.request<void>({ return this.request<void>({
path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(requestParameters.orderId)), path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(orderId)),
method: 'DELETE', method: 'DELETE',
}); });
}; };
@ -67,11 +67,11 @@ export class StoreApi extends BaseAPI {
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* Find purchase order by ID * Find purchase order by ID
*/ */
getOrderById = (requestParameters: GetOrderByIdRequest): Observable<Order> => { getOrderById = ({ orderId }: GetOrderByIdRequest): Observable<Order> => {
throwIfRequired(requestParameters, 'orderId', 'getOrderById'); throwIfNullOrUndefined(orderId, 'getOrderById');
return this.request<Order>({ return this.request<Order>({
path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(requestParameters.orderId)), path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(orderId)),
method: 'GET', method: 'GET',
}); });
}; };
@ -79,8 +79,8 @@ export class StoreApi extends BaseAPI {
/** /**
* Place an order for a pet * Place an order for a pet
*/ */
placeOrder = (requestParameters: PlaceOrderRequest): Observable<Order> => { placeOrder = ({ body }: PlaceOrderRequest): Observable<Order> => {
throwIfRequired(requestParameters, 'body', 'placeOrder'); throwIfNullOrUndefined(body, 'placeOrder');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -90,7 +90,7 @@ export class StoreApi extends BaseAPI {
path: '/store/order', path: '/store/order',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };

View File

@ -12,7 +12,7 @@
*/ */
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { BaseAPI, HttpHeaders, HttpQuery, throwIfRequired, encodeURI } from '../runtime'; import { BaseAPI, HttpHeaders, HttpQuery, throwIfNullOrUndefined, encodeURI } from '../runtime';
import { import {
User, User,
} from '../models'; } from '../models';
@ -56,8 +56,8 @@ export class UserApi extends BaseAPI {
* This can only be done by the logged in user. * This can only be done by the logged in user.
* Create user * Create user
*/ */
createUser = (requestParameters: CreateUserRequest): Observable<void> => { createUser = ({ body }: CreateUserRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'createUser'); throwIfNullOrUndefined(body, 'createUser');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -67,15 +67,15 @@ export class UserApi extends BaseAPI {
path: '/user', path: '/user',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Creates list of users with given input array * Creates list of users with given input array
*/ */
createUsersWithArrayInput = (requestParameters: CreateUsersWithArrayInputRequest): Observable<void> => { createUsersWithArrayInput = ({ body }: CreateUsersWithArrayInputRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'createUsersWithArrayInput'); throwIfNullOrUndefined(body, 'createUsersWithArrayInput');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -85,15 +85,15 @@ export class UserApi extends BaseAPI {
path: '/user/createWithArray', path: '/user/createWithArray',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Creates list of users with given input array * Creates list of users with given input array
*/ */
createUsersWithListInput = (requestParameters: CreateUsersWithListInputRequest): Observable<void> => { createUsersWithListInput = ({ body }: CreateUsersWithListInputRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'createUsersWithListInput'); throwIfNullOrUndefined(body, 'createUsersWithListInput');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -103,7 +103,7 @@ export class UserApi extends BaseAPI {
path: '/user/createWithList', path: '/user/createWithList',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
@ -111,11 +111,11 @@ export class UserApi extends BaseAPI {
* This can only be done by the logged in user. * This can only be done by the logged in user.
* Delete user * Delete user
*/ */
deleteUser = (requestParameters: DeleteUserRequest): Observable<void> => { deleteUser = ({ username }: DeleteUserRequest): Observable<void> => {
throwIfRequired(requestParameters, 'username', 'deleteUser'); throwIfNullOrUndefined(username, 'deleteUser');
return this.request<void>({ return this.request<void>({
path: '/user/{username}'.replace('{username}', encodeURI(requestParameters.username)), path: '/user/{username}'.replace('{username}', encodeURI(username)),
method: 'DELETE', method: 'DELETE',
}); });
}; };
@ -123,11 +123,11 @@ export class UserApi extends BaseAPI {
/** /**
* Get user by user name * Get user by user name
*/ */
getUserByName = (requestParameters: GetUserByNameRequest): Observable<User> => { getUserByName = ({ username }: GetUserByNameRequest): Observable<User> => {
throwIfRequired(requestParameters, 'username', 'getUserByName'); throwIfNullOrUndefined(username, 'getUserByName');
return this.request<User>({ return this.request<User>({
path: '/user/{username}'.replace('{username}', encodeURI(requestParameters.username)), path: '/user/{username}'.replace('{username}', encodeURI(username)),
method: 'GET', method: 'GET',
}); });
}; };
@ -135,13 +135,13 @@ export class UserApi extends BaseAPI {
/** /**
* Logs user into the system * Logs user into the system
*/ */
loginUser = (requestParameters: LoginUserRequest): Observable<string> => { loginUser = ({ username, password }: LoginUserRequest): Observable<string> => {
throwIfRequired(requestParameters, 'username', 'loginUser'); throwIfNullOrUndefined(username, 'loginUser');
throwIfRequired(requestParameters, 'password', 'loginUser'); throwIfNullOrUndefined(password, 'loginUser');
const query: HttpQuery = { const query: HttpQuery = { // required parameters are used directly since they are already checked by throwIfNullOrUndefined
...(requestParameters.username && { 'username': requestParameters.username }), 'username': username,
...(requestParameters.password && { 'password': requestParameters.password }), 'password': password,
}; };
return this.request<string>({ return this.request<string>({
@ -165,19 +165,19 @@ export class UserApi extends BaseAPI {
* This can only be done by the logged in user. * This can only be done by the logged in user.
* Updated user * Updated user
*/ */
updateUser = (requestParameters: UpdateUserRequest): Observable<void> => { updateUser = ({ username, body }: UpdateUserRequest): Observable<void> => {
throwIfRequired(requestParameters, 'username', 'updateUser'); throwIfNullOrUndefined(username, 'updateUser');
throwIfRequired(requestParameters, 'body', 'updateUser'); throwIfNullOrUndefined(body, 'updateUser');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}; };
return this.request<void>({ return this.request<void>({
path: '/user/{username}'.replace('{username}', encodeURI(requestParameters.username)), path: '/user/{username}'.replace('{username}', encodeURI(username)),
method: 'PUT', method: 'PUT',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };

View File

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

View File

@ -12,7 +12,7 @@
*/ */
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { BaseAPI, HttpHeaders, HttpQuery, throwIfRequired, encodeURI, COLLECTION_FORMATS } from '../runtime'; import { BaseAPI, HttpHeaders, HttpQuery, throwIfNullOrUndefined, encodeURI, COLLECTION_FORMATS } from '../runtime';
import { import {
ApiResponse, ApiResponse,
Pet, Pet,
@ -63,45 +63,47 @@ export class PetApi extends BaseAPI {
/** /**
* Add a new pet to the store * Add a new pet to the store
*/ */
addPet = (requestParameters: AddPetRequest): Observable<void> => { addPet = ({ body }: AddPetRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'addPet'); throwIfNullOrUndefined(body, 'addPet');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
return this.request<void>({ return this.request<void>({
path: '/pet', path: '/pet',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Deletes a pet * Deletes a pet
*/ */
deletePet = (requestParameters: DeletePetRequest): Observable<void> => { deletePet = ({ petId, apiKey }: DeletePetRequest): Observable<void> => {
throwIfRequired(requestParameters, 'petId', 'deletePet'); throwIfNullOrUndefined(petId, 'deletePet');
const headers: HttpHeaders = { const headers: HttpHeaders = {
...(requestParameters.apiKey && { 'api_key': String(requestParameters.apiKey) }), ...(apiKey != null ? { 'api_key': String(apiKey) } : undefined),
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
return this.request<void>({ return this.request<void>({
path: '/pet/{petId}'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}'.replace('{petId}', encodeURI(petId)),
method: 'DELETE', method: 'DELETE',
headers, headers,
}); });
@ -111,20 +113,21 @@ export class PetApi extends BaseAPI {
* Multiple status values can be provided with comma separated strings * Multiple status values can be provided with comma separated strings
* Finds Pets by status * Finds Pets by status
*/ */
findPetsByStatus = (requestParameters: FindPetsByStatusRequest): Observable<Array<Pet>> => { findPetsByStatus = ({ status }: FindPetsByStatusRequest): Observable<Array<Pet>> => {
throwIfRequired(requestParameters, 'status', 'findPetsByStatus'); throwIfNullOrUndefined(status, 'findPetsByStatus');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const query: HttpQuery = { const query: HttpQuery = { // required parameters are used directly since they are already checked by throwIfNullOrUndefined
...(requestParameters.status && { 'status': requestParameters.status.join(COLLECTION_FORMATS['csv']) }), 'status': status.join(COLLECTION_FORMATS['csv']),
}; };
return this.request<Array<Pet>>({ return this.request<Array<Pet>>({
@ -139,20 +142,21 @@ export class PetApi extends BaseAPI {
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* Finds Pets by tags * Finds Pets by tags
*/ */
findPetsByTags = (requestParameters: FindPetsByTagsRequest): Observable<Array<Pet>> => { findPetsByTags = ({ tags }: FindPetsByTagsRequest): Observable<Array<Pet>> => {
throwIfRequired(requestParameters, 'tags', 'findPetsByTags'); throwIfNullOrUndefined(tags, 'findPetsByTags');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const query: HttpQuery = { const query: HttpQuery = { // required parameters are used directly since they are already checked by throwIfNullOrUndefined
...(requestParameters.tags && { 'tags': requestParameters.tags.join(COLLECTION_FORMATS['csv']) }), 'tags': tags.join(COLLECTION_FORMATS['csv']),
}; };
return this.request<Array<Pet>>({ return this.request<Array<Pet>>({
@ -167,15 +171,15 @@ export class PetApi extends BaseAPI {
* Returns a single pet * Returns a single pet
* Find pet by ID * Find pet by ID
*/ */
getPetById = (requestParameters: GetPetByIdRequest): Observable<Pet> => { getPetById = ({ petId }: GetPetByIdRequest): Observable<Pet> => {
throwIfRequired(requestParameters, 'petId', 'getPetById'); throwIfNullOrUndefined(petId, 'getPetById');
const headers: HttpHeaders = { const headers: HttpHeaders = {
...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication ...(this.configuration.apiKey && { 'api_key': this.configuration.apiKey('api_key') }), // api_key authentication
}; };
return this.request<Pet>({ return this.request<Pet>({
path: '/pet/{petId}'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}'.replace('{petId}', encodeURI(petId)),
method: 'GET', method: 'GET',
headers, headers,
}); });
@ -184,53 +188,50 @@ export class PetApi extends BaseAPI {
/** /**
* Update an existing pet * Update an existing pet
*/ */
updatePet = (requestParameters: UpdatePetRequest): Observable<void> => { updatePet = ({ body }: UpdatePetRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'updatePet'); throwIfNullOrUndefined(body, 'updatePet');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
return this.request<void>({ return this.request<void>({
path: '/pet', path: '/pet',
method: 'PUT', method: 'PUT',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Updates a pet in the store with form data * Updates a pet in the store with form data
*/ */
updatePetWithForm = (requestParameters: UpdatePetWithFormRequest): Observable<void> => { updatePetWithForm = ({ petId, name, status }: UpdatePetWithFormRequest): Observable<void> => {
throwIfRequired(requestParameters, 'petId', 'updatePetWithForm'); throwIfNullOrUndefined(petId, 'updatePetWithForm');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const formData = new FormData(); const formData = new FormData();
if (requestParameters.name !== undefined) { if (name !== undefined) { formData.append('name', name as any); }
formData.append('name', requestParameters.name as any); if (status !== undefined) { formData.append('status', status as any); }
}
if (requestParameters.status !== undefined) {
formData.append('status', requestParameters.status as any);
}
return this.request<void>({ return this.request<void>({
path: '/pet/{petId}'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}'.replace('{petId}', encodeURI(petId)),
method: 'POST', method: 'POST',
headers, headers,
body: formData, body: formData,
@ -240,29 +241,25 @@ export class PetApi extends BaseAPI {
/** /**
* uploads an image * uploads an image
*/ */
uploadFile = (requestParameters: UploadFileRequest): Observable<ApiResponse> => { uploadFile = ({ petId, additionalMetadata, file }: UploadFileRequest): Observable<ApiResponse> => {
throwIfRequired(requestParameters, 'petId', 'uploadFile'); throwIfNullOrUndefined(petId, 'uploadFile');
const headers: HttpHeaders = { const headers: HttpHeaders = {
// oauth required // oauth required
...(this.configuration.accessToken && { ...(this.configuration.accessToken != null
Authorization: this.configuration.accessToken && (typeof this.configuration.accessToken === 'function' ? { Authorization: typeof this.configuration.accessToken === 'function'
? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets']) ? this.configuration.accessToken('petstore_auth', ['write:pets', 'read:pets'])
: this.configuration.accessToken) : this.configuration.accessToken }
}), : undefined
),
}; };
const formData = new FormData(); const formData = new FormData();
if (requestParameters.additionalMetadata !== undefined) { if (additionalMetadata !== undefined) { formData.append('additionalMetadata', additionalMetadata as any); }
formData.append('additionalMetadata', requestParameters.additionalMetadata as any); if (file !== undefined) { formData.append('file', file as any); }
}
if (requestParameters.file !== undefined) {
formData.append('file', requestParameters.file as any);
}
return this.request<ApiResponse>({ return this.request<ApiResponse>({
path: '/pet/{petId}/uploadImage'.replace('{petId}', encodeURI(requestParameters.petId)), path: '/pet/{petId}/uploadImage'.replace('{petId}', encodeURI(petId)),
method: 'POST', method: 'POST',
headers, headers,
body: formData, body: formData,

View File

@ -12,7 +12,7 @@
*/ */
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { BaseAPI, HttpHeaders, throwIfRequired, encodeURI } from '../runtime'; import { BaseAPI, HttpHeaders, throwIfNullOrUndefined, encodeURI } from '../runtime';
import { import {
Order, Order,
} from '../models'; } from '../models';
@ -38,11 +38,11 @@ export class StoreApi extends BaseAPI {
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
* Delete purchase order by ID * Delete purchase order by ID
*/ */
deleteOrder = (requestParameters: DeleteOrderRequest): Observable<void> => { deleteOrder = ({ orderId }: DeleteOrderRequest): Observable<void> => {
throwIfRequired(requestParameters, 'orderId', 'deleteOrder'); throwIfNullOrUndefined(orderId, 'deleteOrder');
return this.request<void>({ return this.request<void>({
path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(requestParameters.orderId)), path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(orderId)),
method: 'DELETE', method: 'DELETE',
}); });
}; };
@ -67,11 +67,11 @@ export class StoreApi extends BaseAPI {
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
* Find purchase order by ID * Find purchase order by ID
*/ */
getOrderById = (requestParameters: GetOrderByIdRequest): Observable<Order> => { getOrderById = ({ orderId }: GetOrderByIdRequest): Observable<Order> => {
throwIfRequired(requestParameters, 'orderId', 'getOrderById'); throwIfNullOrUndefined(orderId, 'getOrderById');
return this.request<Order>({ return this.request<Order>({
path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(requestParameters.orderId)), path: '/store/order/{orderId}'.replace('{orderId}', encodeURI(orderId)),
method: 'GET', method: 'GET',
}); });
}; };
@ -79,8 +79,8 @@ export class StoreApi extends BaseAPI {
/** /**
* Place an order for a pet * Place an order for a pet
*/ */
placeOrder = (requestParameters: PlaceOrderRequest): Observable<Order> => { placeOrder = ({ body }: PlaceOrderRequest): Observable<Order> => {
throwIfRequired(requestParameters, 'body', 'placeOrder'); throwIfNullOrUndefined(body, 'placeOrder');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -90,7 +90,7 @@ export class StoreApi extends BaseAPI {
path: '/store/order', path: '/store/order',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };

View File

@ -12,7 +12,7 @@
*/ */
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import { BaseAPI, HttpHeaders, HttpQuery, throwIfRequired, encodeURI } from '../runtime'; import { BaseAPI, HttpHeaders, HttpQuery, throwIfNullOrUndefined, encodeURI } from '../runtime';
import { import {
User, User,
} from '../models'; } from '../models';
@ -56,8 +56,8 @@ export class UserApi extends BaseAPI {
* This can only be done by the logged in user. * This can only be done by the logged in user.
* Create user * Create user
*/ */
createUser = (requestParameters: CreateUserRequest): Observable<void> => { createUser = ({ body }: CreateUserRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'createUser'); throwIfNullOrUndefined(body, 'createUser');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -67,15 +67,15 @@ export class UserApi extends BaseAPI {
path: '/user', path: '/user',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Creates list of users with given input array * Creates list of users with given input array
*/ */
createUsersWithArrayInput = (requestParameters: CreateUsersWithArrayInputRequest): Observable<void> => { createUsersWithArrayInput = ({ body }: CreateUsersWithArrayInputRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'createUsersWithArrayInput'); throwIfNullOrUndefined(body, 'createUsersWithArrayInput');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -85,15 +85,15 @@ export class UserApi extends BaseAPI {
path: '/user/createWithArray', path: '/user/createWithArray',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
/** /**
* Creates list of users with given input array * Creates list of users with given input array
*/ */
createUsersWithListInput = (requestParameters: CreateUsersWithListInputRequest): Observable<void> => { createUsersWithListInput = ({ body }: CreateUsersWithListInputRequest): Observable<void> => {
throwIfRequired(requestParameters, 'body', 'createUsersWithListInput'); throwIfNullOrUndefined(body, 'createUsersWithListInput');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
@ -103,7 +103,7 @@ export class UserApi extends BaseAPI {
path: '/user/createWithList', path: '/user/createWithList',
method: 'POST', method: 'POST',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };
@ -111,11 +111,11 @@ export class UserApi extends BaseAPI {
* This can only be done by the logged in user. * This can only be done by the logged in user.
* Delete user * Delete user
*/ */
deleteUser = (requestParameters: DeleteUserRequest): Observable<void> => { deleteUser = ({ username }: DeleteUserRequest): Observable<void> => {
throwIfRequired(requestParameters, 'username', 'deleteUser'); throwIfNullOrUndefined(username, 'deleteUser');
return this.request<void>({ return this.request<void>({
path: '/user/{username}'.replace('{username}', encodeURI(requestParameters.username)), path: '/user/{username}'.replace('{username}', encodeURI(username)),
method: 'DELETE', method: 'DELETE',
}); });
}; };
@ -123,11 +123,11 @@ export class UserApi extends BaseAPI {
/** /**
* Get user by user name * Get user by user name
*/ */
getUserByName = (requestParameters: GetUserByNameRequest): Observable<User> => { getUserByName = ({ username }: GetUserByNameRequest): Observable<User> => {
throwIfRequired(requestParameters, 'username', 'getUserByName'); throwIfNullOrUndefined(username, 'getUserByName');
return this.request<User>({ return this.request<User>({
path: '/user/{username}'.replace('{username}', encodeURI(requestParameters.username)), path: '/user/{username}'.replace('{username}', encodeURI(username)),
method: 'GET', method: 'GET',
}); });
}; };
@ -135,13 +135,13 @@ export class UserApi extends BaseAPI {
/** /**
* Logs user into the system * Logs user into the system
*/ */
loginUser = (requestParameters: LoginUserRequest): Observable<string> => { loginUser = ({ username, password }: LoginUserRequest): Observable<string> => {
throwIfRequired(requestParameters, 'username', 'loginUser'); throwIfNullOrUndefined(username, 'loginUser');
throwIfRequired(requestParameters, 'password', 'loginUser'); throwIfNullOrUndefined(password, 'loginUser');
const query: HttpQuery = { const query: HttpQuery = { // required parameters are used directly since they are already checked by throwIfNullOrUndefined
...(requestParameters.username && { 'username': requestParameters.username }), 'username': username,
...(requestParameters.password && { 'password': requestParameters.password }), 'password': password,
}; };
return this.request<string>({ return this.request<string>({
@ -165,19 +165,19 @@ export class UserApi extends BaseAPI {
* This can only be done by the logged in user. * This can only be done by the logged in user.
* Updated user * Updated user
*/ */
updateUser = (requestParameters: UpdateUserRequest): Observable<void> => { updateUser = ({ username, body }: UpdateUserRequest): Observable<void> => {
throwIfRequired(requestParameters, 'username', 'updateUser'); throwIfNullOrUndefined(username, 'updateUser');
throwIfRequired(requestParameters, 'body', 'updateUser'); throwIfNullOrUndefined(body, 'updateUser');
const headers: HttpHeaders = { const headers: HttpHeaders = {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}; };
return this.request<void>({ return this.request<void>({
path: '/user/{username}'.replace('{username}', encodeURI(requestParameters.username)), path: '/user/{username}'.replace('{username}', encodeURI(username)),
method: 'PUT', method: 'PUT',
headers, headers,
body: requestParameters.body, body: body,
}); });
}; };

View File

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