diff --git a/bin/configs/typescript-fetch-without-runtime-checks.yaml b/bin/configs/typescript-fetch-without-runtime-checks.yaml new file mode 100644 index 000000000000..15505a8986e9 --- /dev/null +++ b/bin/configs/typescript-fetch-without-runtime-checks.yaml @@ -0,0 +1,9 @@ +generatorName: typescript-fetch +outputDir: samples/client/petstore/typescript-fetch/builds/without-runtime-checks +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +additionalProperties: + npmVersion: 1.0.0 + npmName: '@openapitools/typescript-fetch-petstore' + npmRepository: https://skimdb.npmjs.com/registry + withoutRuntimeChecks: true + snapshot: false diff --git a/docs/generators/typescript-fetch.md b/docs/generators/typescript-fetch.md index 6aa54572fa19..14e40978db6d 100644 --- a/docs/generators/typescript-fetch.md +++ b/docs/generators/typescript-fetch.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |typescriptThreePlus|Setting this property to true will generate TypeScript 3.6+ compatible code.| |false| |useSingleRequestParameter|Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter.| |true| |withInterfaces|Setting this property to true will generate interfaces next to the default class implementations.| |false| +|withoutRuntimeChecks|Setting this property to true will remove any runtime checks on the request and response payloads. Payloads will be casted to their expected types.| |false| ## IMPORT MAPPING diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java index 35c31b66e3d5..cf591520be99 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java @@ -39,6 +39,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege public static final String USE_SINGLE_REQUEST_PARAMETER = "useSingleRequestParameter"; public static final String PREFIX_PARAMETER_INTERFACES = "prefixParameterInterfaces"; public static final String TYPESCRIPT_THREE_PLUS = "typescriptThreePlus"; + public static final String WITHOUT_RUNTIME_CHECKS = "withoutRuntimeChecks"; protected String npmRepository = null; private boolean useSingleRequestParameter = true; @@ -46,6 +47,7 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege protected boolean addedApiIndex = false; protected boolean addedModelIndex = false; protected boolean typescriptThreePlus = false; + protected boolean withoutRuntimeChecks = false; public TypeScriptFetchClientCodegen() { @@ -61,7 +63,7 @@ public TypeScriptFetchClientCodegen() { embeddedTemplateDir = templateDir = "typescript-fetch"; this.apiTemplateFiles.put("apis.mustache", ".ts"); - this.modelTemplateFiles.put("models.mustache", ".ts"); + this.addExtraReservedWords(); typeMapping.put("date", "Date"); @@ -73,6 +75,7 @@ public TypeScriptFetchClientCodegen() { this.cliOptions.add(new CliOption(CodegenConstants.USE_SINGLE_REQUEST_PARAMETER, CodegenConstants.USE_SINGLE_REQUEST_PARAMETER_DESC, SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.TRUE.toString())); this.cliOptions.add(new CliOption(PREFIX_PARAMETER_INTERFACES, "Setting this property to true will generate parameter interface declarations prefixed with API class name to avoid name conflicts.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); this.cliOptions.add(new CliOption(TYPESCRIPT_THREE_PLUS, "Setting this property to true will generate TypeScript 3.6+ compatible code.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); + this.cliOptions.add(new CliOption(WITHOUT_RUNTIME_CHECKS, "Setting this property to true will remove any runtime checks on the request and response payloads. Payloads will be casted to their expected types.", SchemaTypeUtil.BOOLEAN_TYPE).defaultValue(Boolean.FALSE.toString())); } @Override @@ -101,6 +104,14 @@ public void setTypescriptThreePlus(Boolean typescriptThreePlus) { this.typescriptThreePlus = typescriptThreePlus; } + public Boolean getWithoutRuntimeChecks(){ + return withoutRuntimeChecks; + } + + public void setWithoutRuntimeChecks(Boolean withoutRuntimeChecks){ + this.withoutRuntimeChecks = withoutRuntimeChecks; + } + @Override public void processOpts() { super.processOpts(); @@ -135,6 +146,14 @@ public void processOpts() { if (additionalProperties.containsKey(TYPESCRIPT_THREE_PLUS)) { this.setTypescriptThreePlus(convertPropertyToBoolean(TYPESCRIPT_THREE_PLUS)); } + + if (additionalProperties.containsKey(WITHOUT_RUNTIME_CHECKS)) { + this.setWithoutRuntimeChecks(convertPropertyToBoolean(WITHOUT_RUNTIME_CHECKS)); + } + + if(!withoutRuntimeChecks){ + this.modelTemplateFiles.put("models.mustache", ".ts"); + } } @Override diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache index 70337db0e275..58bd1d6080b5 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache @@ -7,8 +7,10 @@ import * as runtime from '../runtime'; import { {{#imports}} {{className}}, + {{^withoutRuntimeChecks}} {{className}}FromJSON, {{className}}ToJSON, + {{/withoutRuntimeChecks}} {{/imports}} } from '../models'; {{/imports.0}} @@ -242,7 +244,11 @@ export class {{classname}} extends runtime.BaseAPI { formParams.append('{{baseName}}', requestParameters.{{paramName}} as any); {{/isPrimitiveType}} {{^isPrimitiveType}} + {{^withoutRuntimeChecks}} formParams.append('{{baseName}}', new Blob([JSON.stringify({{{dataType}}}ToJSON(requestParameters.{{paramName}}))], { type: "application/json", })); + {{/withoutRuntimeChecks}}{{#withoutRuntimeChecks}} + formParams.append('{{baseName}}', new Blob([JSON.stringify(requestParameters.{{paramName}})], { type: "application/json", })); + {{/withoutRuntimeChecks}} {{/isPrimitiveType}} } @@ -257,11 +263,21 @@ export class {{classname}} extends runtime.BaseAPI { {{#hasBodyParam}} {{#bodyParam}} {{#isContainer}} + {{^withoutRuntimeChecks}} body: requestParameters.{{paramName}}{{#isArray}}{{#items}}{{^isPrimitiveType}}.map({{datatype}}ToJSON){{/isPrimitiveType}}{{/items}}{{/isArray}}, + {{/withoutRuntimeChecks}} + {{#withoutRuntimeChecks}} + body: requestParameters.{{paramName}}{{#isArray}}{{#items}}{{^isPrimitiveType}}{{/isPrimitiveType}}{{/items}}{{/isArray}}, + {{/withoutRuntimeChecks}} {{/isContainer}} {{^isContainer}} {{^isPrimitiveType}} + {{^withoutRuntimeChecks}} body: {{dataType}}ToJSON(requestParameters.{{paramName}}), + {{/withoutRuntimeChecks}} + {{#withoutRuntimeChecks}} + body: requestParameters.{{paramName}}, + {{/withoutRuntimeChecks}} {{/isPrimitiveType}} {{#isPrimitiveType}} body: requestParameters.{{paramName}} as any, @@ -292,14 +308,14 @@ export class {{classname}} extends runtime.BaseAPI { {{/returnTypeIsPrimitive}} {{^returnTypeIsPrimitive}} {{#isArray}} - return new runtime.JSONApiResponse(response, (jsonValue) => jsonValue.map({{returnBaseType}}FromJSON)); + return new runtime.JSONApiResponse(response{{^withoutRuntimeChecks}}, (jsonValue) => jsonValue.map({{returnBaseType}}FromJSON){{/withoutRuntimeChecks}}); {{/isArray}} {{^isArray}} {{#isMap}} - return new runtime.JSONApiResponse(response, (jsonValue) => runtime.mapValues(jsonValue, {{returnBaseType}}FromJSON)); + return new runtime.JSONApiResponse(response{{^withoutRuntimeChecks}}, (jsonValue) => runtime.mapValues(jsonValue, {{returnBaseType}}FromJSON){{/withoutRuntimeChecks}}); {{/isMap}} {{^isMap}} - return new runtime.JSONApiResponse(response, (jsonValue) => {{returnBaseType}}FromJSON(jsonValue)); + return new runtime.JSONApiResponse(response{{^withoutRuntimeChecks}}, (jsonValue) => {{returnBaseType}}FromJSON(jsonValue){{/withoutRuntimeChecks}}); {{/isMap}} {{/isArray}} {{/returnTypeIsPrimitive}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelEnum.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelEnum.mustache index 7534f9b391a1..55a39a4ff3de 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/modelEnum.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelEnum.mustache @@ -1,15 +1,4 @@ -/** - * {{#lambda.indented_star_1}}{{{unescapedDescription}}}{{/lambda.indented_star_1}} - * @export - * @enum {string} - */ -export enum {{classname}} { -{{#allowableValues}} -{{#enumVars}} - {{{name}}} = {{{value}}}{{^-last}},{{/-last}} -{{/enumVars}} -{{/allowableValues}} -} +{{>modelEnumInterfaces}} export function {{classname}}FromJSON(json: any): {{classname}} { return {{classname}}FromJSONTyped(json, false); diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelEnumInterfaces.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelEnumInterfaces.mustache new file mode 100644 index 000000000000..1679554d3583 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelEnumInterfaces.mustache @@ -0,0 +1,12 @@ +/** + * {{#lambda.indented_star_1}}{{{unescapedDescription}}}{{/lambda.indented_star_1}} + * @export + * @enum {string} + */ +export enum {{classname}} { +{{#allowableValues}} +{{#enumVars}} + {{{name}}} = {{{value}}}{{^-last}},{{/-last}} +{{/enumVars}} +{{/allowableValues}} +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache index 4ce18a92b519..eec8a9022c73 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache @@ -18,24 +18,7 @@ import { } from './'; {{/discriminator}} -/** - * {{#lambda.indented_star_1}}{{{unescapedDescription}}}{{/lambda.indented_star_1}} - * @export - * @interface {{classname}} - */ -export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ -{{#additionalPropertiesType}} - [key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}}; -{{/additionalPropertiesType}} -{{#vars}} - /** - * {{#lambda.indented_star_4}}{{{unescapedDescription}}}{{/lambda.indented_star_4}} - * @type {{=<% %>=}}{<%&datatype%>}<%={{ }}=%> - * @memberof {{classname}} - */ - {{#isReadOnly}}readonly {{/isReadOnly}}{{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}; -{{/vars}} -} +{{>modelGenericInterfaces}} export function {{classname}}FromJSON(json: any): {{classname}} { return {{classname}}FromJSONTyped(json, false); @@ -145,21 +128,3 @@ export function {{classname}}ToJSON(value?: {{classname}} | null): any { {{/hasVars}} } -{{#hasEnums}} -{{#vars}} -{{#isEnum}} -/** -* @export -* @enum {string} -*/ -export enum {{classname}}{{enumName}} { -{{#allowableValues}} - {{#enumVars}} - {{{name}}} = {{{value}}}{{^-last}},{{/-last}} - {{/enumVars}} -{{/allowableValues}} -} -{{/isEnum}} -{{/vars}} - -{{/hasEnums}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGenericInterfaces.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGenericInterfaces.mustache new file mode 100644 index 000000000000..10e71864ec4d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGenericInterfaces.mustache @@ -0,0 +1,32 @@ +/** + * {{#lambda.indented_star_1}}{{{unescapedDescription}}}{{/lambda.indented_star_1}} + * @export + * @interface {{classname}} + */ +export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ +{{#additionalPropertiesType}} + [key: string]: {{{additionalPropertiesType}}}{{#hasVars}} | any{{/hasVars}}; +{{/additionalPropertiesType}} +{{#vars}} + /** + * {{#lambda.indented_star_4}}{{{unescapedDescription}}}{{/lambda.indented_star_4}} + * @type {{=<% %>=}}{<%&datatype%>}<%={{ }}=%> + * @memberof {{classname}} + */ + {{#isReadOnly}}readonly {{/isReadOnly}}{{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}; +{{/vars}} +}{{#hasEnums}} + +{{#vars}} +{{#isEnum}} +/** +* @export +* @enum {string} +*/ +export enum {{classname}}{{enumName}} { +{{#allowableValues}} + {{#enumVars}} + {{{name}}} = {{{value}}}{{^-last}},{{/-last}} + {{/enumVars}} +{{/allowableValues}} +}{{/isEnum}}{{/vars}}{{/hasEnums}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOf.mustache index 506d8207bc97..12d60088b42c 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOf.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOf.mustache @@ -10,12 +10,7 @@ import { } from './'; {{/hasImports}} -/** - * @type {{classname}} - * {{#lambda.indented_star_1}}{{{unescapedDescription}}}{{/lambda.indented_star_1}} - * @export - */ -export type {{classname}} = {{#discriminator}}{{#mappedModels}}{ {{discriminator.propertyName}}: '{{mappingName}}' } & {{modelName}}{{^-last}} | {{/-last}}{{/mappedModels}}{{/discriminator}}{{^discriminator}}{{#oneOf}}{{{.}}}{{^-last}} | {{/-last}}{{/oneOf}}{{/discriminator}}; +{{>modelOneOfInterfaces}} export function {{classname}}FromJSON(json: any): {{classname}} { return {{classname}}FromJSONTyped(json, false); diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOfInterfaces.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOfInterfaces.mustache new file mode 100644 index 000000000000..ee4d1fccd8eb --- /dev/null +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOfInterfaces.mustache @@ -0,0 +1,6 @@ +/** + * @type {{classname}} + * {{#lambda.indented_star_1}}{{{unescapedDescription}}}{{/lambda.indented_star_1}} + * @export + */ +export type {{classname}} = {{#discriminator}}{{#mappedModels}}{ {{discriminator.propertyName}}: '{{mappingName}}' } & {{modelName}}{{^-last}} | {{/-last}}{{/mappedModels}}{{/discriminator}}{{^discriminator}}{{#oneOf}}{{{.}}}{{^-last}} | {{/-last}}{{/oneOf}}{{/discriminator}}; \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/models.index.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/models.index.mustache index 02a39c248c4d..7331df67ca9e 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/models.index.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/models.index.mustache @@ -1,5 +1,21 @@ {{#models}} {{#model}} +{{^withoutRuntimeChecks}} export * from './{{{ classFilename }}}'; +{{/withoutRuntimeChecks}}{{#withoutRuntimeChecks}} +{{#isEnum}} +{{>modelEnumInterfaces}} +{{/isEnum}} +{{^isEnum}} +{{#oneOf}} +{{#-first}} +{{>modelOneOfInterfaces}} +{{/-first}} +{{/oneOf}} +{{^oneOf}} +{{>modelGenericInterfaces}} +{{/oneOf}} +{{/isEnum}} +{{/withoutRuntimeChecks}} {{/model}} {{/models}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java index 1671fc5293c8..be8e06e79fe2 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/TypeScriptFetchClientOptionsProvider.java @@ -39,6 +39,7 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; public static final String TYPESCRIPT_THREE_PLUS = "true"; + public static final String WITHOUT_RUNTIME_CHECKS = "true"; @Override public String getLanguage() { @@ -64,6 +65,7 @@ public Map createOptions() { .put(TypeScriptFetchClientCodegen.USE_SINGLE_REQUEST_PARAMETER, Boolean.FALSE.toString()) .put(TypeScriptFetchClientCodegen.PREFIX_PARAMETER_INTERFACES, Boolean.FALSE.toString()) .put(TypeScriptFetchClientCodegen.TYPESCRIPT_THREE_PLUS, TYPESCRIPT_THREE_PLUS) + .put(TypeScriptFetchClientCodegen.WITHOUT_RUNTIME_CHECKS, WITHOUT_RUNTIME_CHECKS) .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) .put(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "true") diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java index ec63ae29d729..6bc2631f6e60 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/fetch/TypeScriptFetchClientOptionsTest.java @@ -45,5 +45,6 @@ protected void verifyOptions() { verify(clientCodegen).setSupportsES6(TypeScriptFetchClientOptionsProvider.SUPPORTS_ES6_VALUE); verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); verify(clientCodegen).setTypescriptThreePlus(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.TYPESCRIPT_THREE_PLUS)); + verify(clientCodegen).setWithoutRuntimeChecks(Boolean.valueOf(TypeScriptFetchClientOptionsProvider.WITHOUT_RUNTIME_CHECKS)); } } diff --git a/samples/client/petstore/typescript-fetch/builds/default/models/Order.ts b/samples/client/petstore/typescript-fetch/builds/default/models/Order.ts index 104c3157f61f..79b7455a6177 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/models/Order.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/models/Order.ts @@ -57,6 +57,16 @@ export interface Order { complete?: boolean; } +/** +* @export +* @enum {string} +*/ +export enum OrderStatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' +} + export function OrderFromJSON(json: any): Order { return OrderFromJSONTyped(json, false); } @@ -94,14 +104,4 @@ export function OrderToJSON(value?: Order | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum OrderStatusEnum { - Placed = 'placed', - Approved = 'approved', - Delivered = 'delivered' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/default/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/default/models/Pet.ts index 7e084c084a98..4cb69187ee0c 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/models/Pet.ts @@ -68,6 +68,16 @@ export interface Pet { status?: PetStatusEnum; } +/** +* @export +* @enum {string} +*/ +export enum PetStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} + export function PetFromJSON(json: any): Pet { return PetFromJSONTyped(json, false); } @@ -105,14 +115,4 @@ export function PetToJSON(value?: Pet | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum PetStatusEnum { - Available = 'available', - Pending = 'pending', - Sold = 'sold' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/src/models/Order.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/src/models/Order.ts index 104c3157f61f..79b7455a6177 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/src/models/Order.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/src/models/Order.ts @@ -57,6 +57,16 @@ export interface Order { complete?: boolean; } +/** +* @export +* @enum {string} +*/ +export enum OrderStatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' +} + export function OrderFromJSON(json: any): Order { return OrderFromJSONTyped(json, false); } @@ -94,14 +104,4 @@ export function OrderToJSON(value?: Order | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum OrderStatusEnum { - Placed = 'placed', - Approved = 'approved', - Delivered = 'delivered' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/src/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/src/models/Pet.ts index 7e084c084a98..4cb69187ee0c 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/src/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/src/models/Pet.ts @@ -68,6 +68,16 @@ export interface Pet { status?: PetStatusEnum; } +/** +* @export +* @enum {string} +*/ +export enum PetStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} + export function PetFromJSON(json: any): Pet { return PetFromJSONTyped(json, false); } @@ -105,14 +115,4 @@ export function PetToJSON(value?: Pet | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum PetStatusEnum { - Available = 'available', - Pending = 'pending', - Sold = 'sold' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/models/Order.ts b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/models/Order.ts index 104c3157f61f..79b7455a6177 100644 --- a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/models/Order.ts +++ b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/models/Order.ts @@ -57,6 +57,16 @@ export interface Order { complete?: boolean; } +/** +* @export +* @enum {string} +*/ +export enum OrderStatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' +} + export function OrderFromJSON(json: any): Order { return OrderFromJSONTyped(json, false); } @@ -94,14 +104,4 @@ export function OrderToJSON(value?: Order | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum OrderStatusEnum { - Placed = 'placed', - Approved = 'approved', - Delivered = 'delivered' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/models/Pet.ts index 7e084c084a98..4cb69187ee0c 100644 --- a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/models/Pet.ts @@ -68,6 +68,16 @@ export interface Pet { status?: PetStatusEnum; } +/** +* @export +* @enum {string} +*/ +export enum PetStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} + export function PetFromJSON(json: any): Pet { return PetFromJSONTyped(json, false); } @@ -105,14 +115,4 @@ export function PetToJSON(value?: Pet | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum PetStatusEnum { - Available = 'available', - Pending = 'pending', - Sold = 'sold' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/models/Order.ts b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/models/Order.ts index 104c3157f61f..79b7455a6177 100644 --- a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/models/Order.ts +++ b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/models/Order.ts @@ -57,6 +57,16 @@ export interface Order { complete?: boolean; } +/** +* @export +* @enum {string} +*/ +export enum OrderStatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' +} + export function OrderFromJSON(json: any): Order { return OrderFromJSONTyped(json, false); } @@ -94,14 +104,4 @@ export function OrderToJSON(value?: Order | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum OrderStatusEnum { - Placed = 'placed', - Approved = 'approved', - Delivered = 'delivered' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/models/Pet.ts index 7e084c084a98..4cb69187ee0c 100644 --- a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/models/Pet.ts @@ -68,6 +68,16 @@ export interface Pet { status?: PetStatusEnum; } +/** +* @export +* @enum {string} +*/ +export enum PetStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} + export function PetFromJSON(json: any): Pet { return PetFromJSONTyped(json, false); } @@ -105,14 +115,4 @@ export function PetToJSON(value?: Pet | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum PetStatusEnum { - Available = 'available', - Pending = 'pending', - Sold = 'sold' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/models/Order.ts b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/models/Order.ts index 104c3157f61f..79b7455a6177 100644 --- a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/models/Order.ts +++ b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/models/Order.ts @@ -57,6 +57,16 @@ export interface Order { complete?: boolean; } +/** +* @export +* @enum {string} +*/ +export enum OrderStatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' +} + export function OrderFromJSON(json: any): Order { return OrderFromJSONTyped(json, false); } @@ -94,14 +104,4 @@ export function OrderToJSON(value?: Order | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum OrderStatusEnum { - Placed = 'placed', - Approved = 'approved', - Delivered = 'delivered' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/models/Pet.ts index 7e084c084a98..4cb69187ee0c 100644 --- a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/models/Pet.ts @@ -68,6 +68,16 @@ export interface Pet { status?: PetStatusEnum; } +/** +* @export +* @enum {string} +*/ +export enum PetStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} + export function PetFromJSON(json: any): Pet { return PetFromJSONTyped(json, false); } @@ -105,14 +115,4 @@ export function PetToJSON(value?: Pet | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum PetStatusEnum { - Available = 'available', - Pending = 'pending', - Sold = 'sold' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/models/Order.ts b/samples/client/petstore/typescript-fetch/builds/with-interfaces/models/Order.ts index 104c3157f61f..79b7455a6177 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-interfaces/models/Order.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/models/Order.ts @@ -57,6 +57,16 @@ export interface Order { complete?: boolean; } +/** +* @export +* @enum {string} +*/ +export enum OrderStatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' +} + export function OrderFromJSON(json: any): Order { return OrderFromJSONTyped(json, false); } @@ -94,14 +104,4 @@ export function OrderToJSON(value?: Order | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum OrderStatusEnum { - Placed = 'placed', - Approved = 'approved', - Delivered = 'delivered' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/with-interfaces/models/Pet.ts index 7e084c084a98..4cb69187ee0c 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-interfaces/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/models/Pet.ts @@ -68,6 +68,16 @@ export interface Pet { status?: PetStatusEnum; } +/** +* @export +* @enum {string} +*/ +export enum PetStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} + export function PetFromJSON(json: any): Pet { return PetFromJSONTyped(json, false); } @@ -105,14 +115,4 @@ export function PetToJSON(value?: Pet | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum PetStatusEnum { - Available = 'available', - Pending = 'pending', - Sold = 'sold' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/models/Order.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/models/Order.ts index 104c3157f61f..79b7455a6177 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/models/Order.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/models/Order.ts @@ -57,6 +57,16 @@ export interface Order { complete?: boolean; } +/** +* @export +* @enum {string} +*/ +export enum OrderStatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' +} + export function OrderFromJSON(json: any): Order { return OrderFromJSONTyped(json, false); } @@ -94,14 +104,4 @@ export function OrderToJSON(value?: Order | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum OrderStatusEnum { - Placed = 'placed', - Approved = 'approved', - Delivered = 'delivered' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/models/Pet.ts index 7e084c084a98..4cb69187ee0c 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/models/Pet.ts @@ -68,6 +68,16 @@ export interface Pet { status?: PetStatusEnum; } +/** +* @export +* @enum {string} +*/ +export enum PetStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} + export function PetFromJSON(json: any): Pet { return PetFromJSONTyped(json, false); } @@ -105,14 +115,4 @@ export function PetToJSON(value?: Pet | null): any { }; } -/** -* @export -* @enum {string} -*/ -export enum PetStatusEnum { - Available = 'available', - Pending = 'pending', - Sold = 'sold' -} - diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.gitignore b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.gitignore new file mode 100644 index 000000000000..149b57654723 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.npmignore b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.npmignore new file mode 100644 index 000000000000..42061c01a1c7 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.npmignore @@ -0,0 +1 @@ +README.md \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator-ignore b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/FILES b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/FILES new file mode 100644 index 000000000000..83b6414b911e --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/FILES @@ -0,0 +1,12 @@ +.gitignore +.npmignore +README.md +package.json +src/apis/PetApi.ts +src/apis/StoreApi.ts +src/apis/UserApi.ts +src/apis/index.ts +src/index.ts +src/models/index.ts +src/runtime.ts +tsconfig.json diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/VERSION new file mode 100644 index 000000000000..d99e7162d01f --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/README.md b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/README.md new file mode 100644 index 000000000000..8c188be0ead2 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/README.md @@ -0,0 +1,45 @@ +## @openapitools/typescript-fetch-petstore@1.0.0 + +This generator creates TypeScript/JavaScript client that utilizes [Fetch API](https://fetch.spec.whatwg.org/). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Building + +To build and compile the typescript sources to javascript use: +``` +npm install +npm run build +``` + +### Publishing + +First build the package then run ```npm publish``` + +### Consuming + +navigate to the folder of your consuming project and run one of the following commands. + +_published:_ + +``` +npm install @openapitools/typescript-fetch-petstore@1.0.0 --save +``` + +_unPublished (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE --save diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/package.json b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/package.json new file mode 100644 index 000000000000..478c94e3f2e2 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/package.json @@ -0,0 +1,18 @@ +{ + "name": "@openapitools/typescript-fetch-petstore", + "version": "1.0.0", + "description": "OpenAPI client for @openapitools/typescript-fetch-petstore", + "author": "OpenAPI-Generator", + "main": "./dist/index.js", + "typings": "./dist/index.d.ts", + "scripts": { + "build": "tsc", + "prepare": "npm run build" + }, + "devDependencies": { + "typescript": "^2.4" + }, + "publishConfig": { + "registry": "https://skimdb.npmjs.com/registry" + } +} diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/PetApi.ts new file mode 100644 index 000000000000..dd0a9026b019 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/PetApi.ts @@ -0,0 +1,449 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import * as runtime from '../runtime'; +import { + ModelApiResponse, + Pet, +} from '../models'; + +export interface AddPetRequest { + body: Pet; +} + +export interface DeletePetRequest { + petId: number; + apiKey?: string; +} + +export interface FindPetsByStatusRequest { + status: Array; +} + +export interface FindPetsByTagsRequest { + tags: Array; +} + +export interface GetPetByIdRequest { + petId: number; +} + +export interface UpdatePetRequest { + body: Pet; +} + +export interface UpdatePetWithFormRequest { + petId: number; + name?: string; + status?: string; +} + +export interface UploadFileRequest { + petId: number; + additionalMetadata?: string; + file?: Blob; +} + +/** + * + */ +export class PetApi extends runtime.BaseAPI { + + /** + * Add a new pet to the store + */ + async addPetRaw(requestParameters: AddPetRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling addPet.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const response = await this.request({ + path: `/pet`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: requestParameters.body, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Add a new pet to the store + */ + async addPet(requestParameters: AddPetRequest): Promise { + await this.addPetRaw(requestParameters); + } + + /** + * Deletes a pet + */ + async deletePetRaw(requestParameters: DeletePetRequest): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling deletePet.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (requestParameters.apiKey !== undefined && requestParameters.apiKey !== null) { + headerParameters['api_key'] = String(requestParameters.apiKey); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const response = await this.request({ + path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Deletes a pet + */ + async deletePet(requestParameters: DeletePetRequest): Promise { + await this.deletePetRaw(requestParameters); + } + + /** + * Multiple status values can be provided with comma separated strings + * Finds Pets by status + */ + async findPetsByStatusRaw(requestParameters: FindPetsByStatusRequest): Promise>> { + if (requestParameters.status === null || requestParameters.status === undefined) { + throw new runtime.RequiredError('status','Required parameter requestParameters.status was null or undefined when calling findPetsByStatus.'); + } + + const queryParameters: any = {}; + + if (requestParameters.status) { + queryParameters['status'] = requestParameters.status.join(runtime.COLLECTION_FORMATS["csv"]); + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const response = await this.request({ + path: `/pet/findByStatus`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response); + } + + /** + * Multiple status values can be provided with comma separated strings + * Finds Pets by status + */ + async findPetsByStatus(requestParameters: FindPetsByStatusRequest): Promise> { + const response = await this.findPetsByStatusRaw(requestParameters); + return await response.value(); + } + + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * Finds Pets by tags + */ + async findPetsByTagsRaw(requestParameters: FindPetsByTagsRequest): Promise>> { + if (requestParameters.tags === null || requestParameters.tags === undefined) { + throw new runtime.RequiredError('tags','Required parameter requestParameters.tags was null or undefined when calling findPetsByTags.'); + } + + const queryParameters: any = {}; + + if (requestParameters.tags) { + queryParameters['tags'] = requestParameters.tags.join(runtime.COLLECTION_FORMATS["csv"]); + } + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const response = await this.request({ + path: `/pet/findByTags`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response); + } + + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * Finds Pets by tags + */ + async findPetsByTags(requestParameters: FindPetsByTagsRequest): Promise> { + const response = await this.findPetsByTagsRaw(requestParameters); + return await response.value(); + } + + /** + * Returns a single pet + * Find pet by ID + */ + async getPetByIdRaw(requestParameters: GetPetByIdRequest): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling getPetById.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.apiKey) { + headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication + } + + const response = await this.request({ + path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response); + } + + /** + * Returns a single pet + * Find pet by ID + */ + async getPetById(requestParameters: GetPetByIdRequest): Promise { + const response = await this.getPetByIdRaw(requestParameters); + return await response.value(); + } + + /** + * Update an existing pet + */ + async updatePetRaw(requestParameters: UpdatePetRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updatePet.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const response = await this.request({ + path: `/pet`, + method: 'PUT', + headers: headerParameters, + query: queryParameters, + body: requestParameters.body, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Update an existing pet + */ + async updatePet(requestParameters: UpdatePetRequest): Promise { + await this.updatePetRaw(requestParameters); + } + + /** + * Updates a pet in the store with form data + */ + async updatePetWithFormRaw(requestParameters: UpdatePetWithFormRequest): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling updatePetWithForm.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const consumes: runtime.Consume[] = [ + { contentType: 'application/x-www-form-urlencoded' }, + ]; + // @ts-ignore: canConsumeForm may be unused + const canConsumeForm = runtime.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): any }; + let useForm = false; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new URLSearchParams(); + } + + if (requestParameters.name !== undefined) { + formParams.append('name', requestParameters.name as any); + } + + if (requestParameters.status !== undefined) { + formParams.append('status', requestParameters.status as any); + } + + const response = await this.request({ + path: `/pet/{petId}`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: formParams, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Updates a pet in the store with form data + */ + async updatePetWithForm(requestParameters: UpdatePetWithFormRequest): Promise { + await this.updatePetWithFormRaw(requestParameters); + } + + /** + * uploads an image + */ + async uploadFileRaw(requestParameters: UploadFileRequest): Promise> { + if (requestParameters.petId === null || requestParameters.petId === undefined) { + throw new runtime.RequiredError('petId','Required parameter requestParameters.petId was null or undefined when calling uploadFile.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + if (typeof this.configuration.accessToken === 'function') { + headerParameters["Authorization"] = this.configuration.accessToken("petstore_auth", ["write:pets", "read:pets"]); + } else { + headerParameters["Authorization"] = this.configuration.accessToken; + } + } + + const consumes: runtime.Consume[] = [ + { contentType: 'multipart/form-data' }, + ]; + // @ts-ignore: canConsumeForm may be unused + const canConsumeForm = runtime.canConsumeForm(consumes); + + let formParams: { append(param: string, value: any): any }; + let useForm = false; + // use FormData to transmit files using content-type "multipart/form-data" + useForm = canConsumeForm; + if (useForm) { + formParams = new FormData(); + } else { + formParams = new URLSearchParams(); + } + + if (requestParameters.additionalMetadata !== undefined) { + formParams.append('additionalMetadata', requestParameters.additionalMetadata as any); + } + + if (requestParameters.file !== undefined) { + formParams.append('file', requestParameters.file as any); + } + + const response = await this.request({ + path: `/pet/{petId}/uploadImage`.replace(`{${"petId"}}`, encodeURIComponent(String(requestParameters.petId))), + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: formParams, + }); + + return new runtime.JSONApiResponse(response); + } + + /** + * uploads an image + */ + async uploadFile(requestParameters: UploadFileRequest): Promise { + const response = await this.uploadFileRaw(requestParameters); + return await response.value(); + } + +} + +/** + * @export + * @enum {string} + */ +export enum FindPetsByStatusStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/StoreApi.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/StoreApi.ts new file mode 100644 index 000000000000..206cebc42a48 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/StoreApi.ts @@ -0,0 +1,166 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import * as runtime from '../runtime'; +import { + Order, +} from '../models'; + +export interface DeleteOrderRequest { + orderId: string; +} + +export interface GetOrderByIdRequest { + orderId: number; +} + +export interface PlaceOrderRequest { + body: Order; +} + +/** + * + */ +export class StoreApi extends runtime.BaseAPI { + + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * Delete purchase order by ID + */ + async deleteOrderRaw(requestParameters: DeleteOrderRequest): Promise> { + if (requestParameters.orderId === null || requestParameters.orderId === undefined) { + throw new runtime.RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling deleteOrder.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * Delete purchase order by ID + */ + async deleteOrder(requestParameters: DeleteOrderRequest): Promise { + await this.deleteOrderRaw(requestParameters); + } + + /** + * Returns a map of status codes to quantities + * Returns pet inventories by status + */ + async getInventoryRaw(): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.apiKey) { + headerParameters["api_key"] = this.configuration.apiKey("api_key"); // api_key authentication + } + + const response = await this.request({ + path: `/store/inventory`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response); + } + + /** + * Returns a map of status codes to quantities + * Returns pet inventories by status + */ + async getInventory(): Promise<{ [key: string]: number; }> { + const response = await this.getInventoryRaw(); + return await response.value(); + } + + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * Find purchase order by ID + */ + async getOrderByIdRaw(requestParameters: GetOrderByIdRequest): Promise> { + if (requestParameters.orderId === null || requestParameters.orderId === undefined) { + throw new runtime.RequiredError('orderId','Required parameter requestParameters.orderId was null or undefined when calling getOrderById.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/store/order/{orderId}`.replace(`{${"orderId"}}`, encodeURIComponent(String(requestParameters.orderId))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response); + } + + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * Find purchase order by ID + */ + async getOrderById(requestParameters: GetOrderByIdRequest): Promise { + const response = await this.getOrderByIdRaw(requestParameters); + return await response.value(); + } + + /** + * Place an order for a pet + */ + async placeOrderRaw(requestParameters: PlaceOrderRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling placeOrder.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/store/order`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: requestParameters.body, + }); + + return new runtime.JSONApiResponse(response); + } + + /** + * Place an order for a pet + */ + async placeOrder(requestParameters: PlaceOrderRequest): Promise { + const response = await this.placeOrderRaw(requestParameters); + return await response.value(); + } + +} diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/UserApi.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/UserApi.ts new file mode 100644 index 000000000000..a0c7433ad669 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/UserApi.ts @@ -0,0 +1,320 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import * as runtime from '../runtime'; +import { + User, +} from '../models'; + +export interface CreateUserRequest { + body: User; +} + +export interface CreateUsersWithArrayInputRequest { + body: Array; +} + +export interface CreateUsersWithListInputRequest { + body: Array; +} + +export interface DeleteUserRequest { + username: string; +} + +export interface GetUserByNameRequest { + username: string; +} + +export interface LoginUserRequest { + username: string; + password: string; +} + +export interface UpdateUserRequest { + username: string; + body: User; +} + +/** + * + */ +export class UserApi extends runtime.BaseAPI { + + /** + * This can only be done by the logged in user. + * Create user + */ + async createUserRaw(requestParameters: CreateUserRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUser.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/user`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: requestParameters.body, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * This can only be done by the logged in user. + * Create user + */ + async createUser(requestParameters: CreateUserRequest): Promise { + await this.createUserRaw(requestParameters); + } + + /** + * Creates list of users with given input array + */ + async createUsersWithArrayInputRaw(requestParameters: CreateUsersWithArrayInputRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithArrayInput.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/user/createWithArray`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: requestParameters.body, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Creates list of users with given input array + */ + async createUsersWithArrayInput(requestParameters: CreateUsersWithArrayInputRequest): Promise { + await this.createUsersWithArrayInputRaw(requestParameters); + } + + /** + * Creates list of users with given input array + */ + async createUsersWithListInputRaw(requestParameters: CreateUsersWithListInputRequest): Promise> { + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling createUsersWithListInput.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/user/createWithList`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: requestParameters.body, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Creates list of users with given input array + */ + async createUsersWithListInput(requestParameters: CreateUsersWithListInputRequest): Promise { + await this.createUsersWithListInputRaw(requestParameters); + } + + /** + * This can only be done by the logged in user. + * Delete user + */ + async deleteUserRaw(requestParameters: DeleteUserRequest): Promise> { + if (requestParameters.username === null || requestParameters.username === undefined) { + throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling deleteUser.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * This can only be done by the logged in user. + * Delete user + */ + async deleteUser(requestParameters: DeleteUserRequest): Promise { + await this.deleteUserRaw(requestParameters); + } + + /** + * Get user by user name + */ + async getUserByNameRaw(requestParameters: GetUserByNameRequest): Promise> { + if (requestParameters.username === null || requestParameters.username === undefined) { + throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling getUserByName.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.JSONApiResponse(response); + } + + /** + * Get user by user name + */ + async getUserByName(requestParameters: GetUserByNameRequest): Promise { + const response = await this.getUserByNameRaw(requestParameters); + return await response.value(); + } + + /** + * Logs user into the system + */ + async loginUserRaw(requestParameters: LoginUserRequest): Promise> { + if (requestParameters.username === null || requestParameters.username === undefined) { + throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling loginUser.'); + } + + if (requestParameters.password === null || requestParameters.password === undefined) { + throw new runtime.RequiredError('password','Required parameter requestParameters.password was null or undefined when calling loginUser.'); + } + + const queryParameters: any = {}; + + if (requestParameters.username !== undefined) { + queryParameters['username'] = requestParameters.username; + } + + if (requestParameters.password !== undefined) { + queryParameters['password'] = requestParameters.password; + } + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/user/login`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.TextApiResponse(response) as any; + } + + /** + * Logs user into the system + */ + async loginUser(requestParameters: LoginUserRequest): Promise { + const response = await this.loginUserRaw(requestParameters); + return await response.value(); + } + + /** + * Logs out current logged in user session + */ + async logoutUserRaw(): Promise> { + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + const response = await this.request({ + path: `/user/logout`, + method: 'GET', + headers: headerParameters, + query: queryParameters, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * Logs out current logged in user session + */ + async logoutUser(): Promise { + await this.logoutUserRaw(); + } + + /** + * This can only be done by the logged in user. + * Updated user + */ + async updateUserRaw(requestParameters: UpdateUserRequest): Promise> { + if (requestParameters.username === null || requestParameters.username === undefined) { + throw new runtime.RequiredError('username','Required parameter requestParameters.username was null or undefined when calling updateUser.'); + } + + if (requestParameters.body === null || requestParameters.body === undefined) { + throw new runtime.RequiredError('body','Required parameter requestParameters.body was null or undefined when calling updateUser.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/user/{username}`.replace(`{${"username"}}`, encodeURIComponent(String(requestParameters.username))), + method: 'PUT', + headers: headerParameters, + query: queryParameters, + body: requestParameters.body, + }); + + return new runtime.VoidApiResponse(response); + } + + /** + * This can only be done by the logged in user. + * Updated user + */ + async updateUser(requestParameters: UpdateUserRequest): Promise { + await this.updateUserRaw(requestParameters); + } + +} diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/index.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/index.ts new file mode 100644 index 000000000000..056206bfaca3 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/index.ts @@ -0,0 +1,3 @@ +export * from './PetApi'; +export * from './StoreApi'; +export * from './UserApi'; diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/index.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/index.ts new file mode 100644 index 000000000000..848ecfa4d100 --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/index.ts @@ -0,0 +1,3 @@ +export * from './runtime'; +export * from './apis'; +export * from './models'; diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/index.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/index.ts new file mode 100644 index 000000000000..92ab264fa9cc --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/models/index.ts @@ -0,0 +1,230 @@ + +/** + * A category for a pet + * @export + * @interface Category + */ +export interface Category { + /** + * + * @type {number} + * @memberof Category + */ + id?: number; + /** + * + * @type {string} + * @memberof Category + */ + name?: string; +} + +/** + * Describes the result of uploading an image resource + * @export + * @interface ModelApiResponse + */ +export interface ModelApiResponse { + /** + * + * @type {number} + * @memberof ModelApiResponse + */ + code?: number; + /** + * + * @type {string} + * @memberof ModelApiResponse + */ + type?: string; + /** + * + * @type {string} + * @memberof ModelApiResponse + */ + message?: string; +} + +/** + * An order for a pets from the pet store + * @export + * @interface Order + */ +export interface Order { + /** + * + * @type {number} + * @memberof Order + */ + id?: number; + /** + * + * @type {number} + * @memberof Order + */ + petId?: number; + /** + * + * @type {number} + * @memberof Order + */ + quantity?: number; + /** + * + * @type {Date} + * @memberof Order + */ + shipDate?: Date; + /** + * Order Status + * @type {string} + * @memberof Order + */ + status?: OrderStatusEnum; + /** + * + * @type {boolean} + * @memberof Order + */ + complete?: boolean; +} + +/** +* @export +* @enum {string} +*/ +export enum OrderStatusEnum { + Placed = 'placed', + Approved = 'approved', + Delivered = 'delivered' +} + +/** + * A pet for sale in the pet store + * @export + * @interface Pet + */ +export interface Pet { + /** + * + * @type {number} + * @memberof Pet + */ + id?: number; + /** + * + * @type {Category} + * @memberof Pet + */ + category?: Category; + /** + * + * @type {string} + * @memberof Pet + */ + name: string; + /** + * + * @type {Array} + * @memberof Pet + */ + photoUrls: Array; + /** + * + * @type {Array} + * @memberof Pet + */ + tags?: Array; + /** + * pet status in the store + * @type {string} + * @memberof Pet + */ + status?: PetStatusEnum; +} + +/** +* @export +* @enum {string} +*/ +export enum PetStatusEnum { + Available = 'available', + Pending = 'pending', + Sold = 'sold' +} + +/** + * A tag for a pet + * @export + * @interface Tag + */ +export interface Tag { + /** + * + * @type {number} + * @memberof Tag + */ + id?: number; + /** + * + * @type {string} + * @memberof Tag + */ + name?: string; +} + +/** + * A User who is purchasing from the pet store + * @export + * @interface User + */ +export interface User { + /** + * + * @type {number} + * @memberof User + */ + id?: number; + /** + * + * @type {string} + * @memberof User + */ + username?: string; + /** + * + * @type {string} + * @memberof User + */ + firstName?: string; + /** + * + * @type {string} + * @memberof User + */ + lastName?: string; + /** + * + * @type {string} + * @memberof User + */ + email?: string; + /** + * + * @type {string} + * @memberof User + */ + password?: string; + /** + * + * @type {string} + * @memberof User + */ + phone?: string; + /** + * User Status + * @type {number} + * @memberof User + */ + userStatus?: number; +} diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts new file mode 100644 index 000000000000..747ca17e206d --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts @@ -0,0 +1,316 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); + +const isBlob = (value: any) => typeof Blob !== 'undefined' && value instanceof Blob; + +/** + * This is the base class for all generated API classes. + */ +export class BaseAPI { + + private middleware: Middleware[]; + + constructor(protected configuration = new Configuration()) { + this.middleware = configuration.middleware; + } + + withMiddleware(this: T, ...middlewares: Middleware[]) { + const next = this.clone(); + next.middleware = next.middleware.concat(...middlewares); + return next; + } + + withPreMiddleware(this: T, ...preMiddlewares: Array) { + const middlewares = preMiddlewares.map((pre) => ({ pre })); + return this.withMiddleware(...middlewares); + } + + withPostMiddleware(this: T, ...postMiddlewares: Array) { + const middlewares = postMiddlewares.map((post) => ({ post })); + return this.withMiddleware(...middlewares); + } + + protected async request(context: RequestOpts): Promise { + const { url, init } = this.createFetchParams(context); + const response = await this.fetchApi(url, init); + if (response.status >= 200 && response.status < 300) { + return response; + } + throw response; + } + + private createFetchParams(context: RequestOpts) { + let url = this.configuration.basePath + context.path; + if (context.query !== undefined && Object.keys(context.query).length !== 0) { + // only add the querystring to the URL if there are query parameters. + // this is done to avoid urls ending with a "?" character which buggy webservers + // do not handle correctly sometimes. + url += '?' + this.configuration.queryParamsStringify(context.query); + } + const body = ((typeof FormData !== "undefined" && context.body instanceof FormData) || context.body instanceof URLSearchParams || isBlob(context.body)) + ? context.body + : JSON.stringify(context.body); + + const headers = Object.assign({}, this.configuration.headers, context.headers); + const init = { + method: context.method, + headers: headers, + body, + credentials: this.configuration.credentials + }; + return { url, init }; + } + + private fetchApi = async (url: string, init: RequestInit) => { + let fetchParams = { url, init }; + for (const middleware of this.middleware) { + if (middleware.pre) { + fetchParams = await middleware.pre({ + fetch: this.fetchApi, + ...fetchParams, + }) || fetchParams; + } + } + let response = await this.configuration.fetchApi(fetchParams.url, fetchParams.init); + for (const middleware of this.middleware) { + if (middleware.post) { + response = await middleware.post({ + fetch: this.fetchApi, + url, + init, + response: response.clone(), + }) || response; + } + } + return response; + } + + /** + * Create a shallow clone of `this` by constructing a new instance + * and then shallow cloning data members. + */ + private clone(this: T): T { + const constructor = this.constructor as any; + const next = new constructor(this.configuration); + next.middleware = this.middleware.slice(); + return next; + } +}; + +export class RequiredError extends Error { + name: "RequiredError" = "RequiredError"; + constructor(public field: string, msg?: string) { + super(msg); + } +} + +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +export type FetchAPI = GlobalFetch['fetch']; + +export interface ConfigurationParameters { + basePath?: string; // override base path + fetchApi?: FetchAPI; // override for fetch implementation + middleware?: Middleware[]; // middleware to apply before/after fetch requests + queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings + username?: string; // parameter for basic security + password?: string; // parameter for basic security + apiKey?: string | ((name: string) => string); // parameter for apiKey security + accessToken?: string | ((name?: string, scopes?: string[]) => string); // parameter for oauth2 security + headers?: HTTPHeaders; //header params we want to use on every request + credentials?: RequestCredentials; //value for the credentials param we want to use on each request +} + +export class Configuration { + constructor(private configuration: ConfigurationParameters = {}) {} + + get basePath(): string { + return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH; + } + + get fetchApi(): FetchAPI { + return this.configuration.fetchApi || window.fetch.bind(window); + } + + get middleware(): Middleware[] { + return this.configuration.middleware || []; + } + + get queryParamsStringify(): (params: HTTPQuery) => string { + return this.configuration.queryParamsStringify || querystring; + } + + get username(): string | undefined { + return this.configuration.username; + } + + get password(): string | undefined { + return this.configuration.password; + } + + get apiKey(): ((name: string) => string) | undefined { + const apiKey = this.configuration.apiKey; + if (apiKey) { + return typeof apiKey === 'function' ? apiKey : () => apiKey; + } + return undefined; + } + + get accessToken(): ((name: string, scopes?: string[]) => string) | undefined { + const accessToken = this.configuration.accessToken; + if (accessToken) { + return typeof accessToken === 'function' ? accessToken : () => accessToken; + } + return undefined; + } + + get headers(): HTTPHeaders | undefined { + return this.configuration.headers; + } + + get credentials(): RequestCredentials | undefined { + return this.configuration.credentials; + } +} + +export type Json = any; +export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD'; +export type HTTPHeaders = { [key: string]: string }; +export type HTTPQuery = { [key: string]: string | number | null | boolean | Array | HTTPQuery }; +export type HTTPBody = Json | FormData | URLSearchParams; +export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original'; + +export interface FetchParams { + url: string; + init: RequestInit; +} + +export interface RequestOpts { + path: string; + method: HTTPMethod; + headers: HTTPHeaders; + query?: HTTPQuery; + body?: HTTPBody; +} + +export function exists(json: any, key: string) { + const value = json[key]; + return value !== null && value !== undefined; +} + +export function querystring(params: HTTPQuery, prefix: string = ''): string { + return Object.keys(params) + .map((key) => { + const fullKey = prefix + (prefix.length ? `[${key}]` : key); + const value = params[key]; + if (value instanceof Array) { + const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue))) + .join(`&${encodeURIComponent(fullKey)}=`); + return `${encodeURIComponent(fullKey)}=${multiValue}`; + } + if (value instanceof Object) { + return querystring(value as HTTPQuery, fullKey); + } + return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`; + }) + .filter(part => part.length > 0) + .join('&'); +} + +export function mapValues(data: any, fn: (item: any) => any) { + return Object.keys(data).reduce( + (acc, key) => ({ ...acc, [key]: fn(data[key]) }), + {} + ); +} + +export function canConsumeForm(consumes: Consume[]): boolean { + for (const consume of consumes) { + if ('multipart/form-data' === consume.contentType) { + return true; + } + } + return false; +} + +export interface Consume { + contentType: string +} + +export interface RequestContext { + fetch: FetchAPI; + url: string; + init: RequestInit; +} + +export interface ResponseContext { + fetch: FetchAPI; + url: string; + init: RequestInit; + response: Response; +} + +export interface Middleware { + pre?(context: RequestContext): Promise; + post?(context: ResponseContext): Promise; +} + +export interface ApiResponse { + raw: Response; + value(): Promise; +} + +export interface ResponseTransformer { + (json: any): T; +} + +export class JSONApiResponse { + constructor(public raw: Response, private transformer: ResponseTransformer = (jsonValue: any) => jsonValue) {} + + async value(): Promise { + return this.transformer(await this.raw.json()); + } +} + +export class VoidApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return undefined; + } +} + +export class BlobApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.blob(); + }; +} + +export class TextApiResponse { + constructor(public raw: Response) {} + + async value(): Promise { + return await this.raw.text(); + }; +} diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/tsconfig.json b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/tsconfig.json new file mode 100644 index 000000000000..4567ec19899a --- /dev/null +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "es5", + "module": "commonjs", + "moduleResolution": "node", + "outDir": "dist", + "lib": [ + "es6", + "dom" + ], + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "dist", + "node_modules" + ] +}